LeetCode 3

Given a string, find the length of the longest substring without repeating characters.

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", which the length is 3.

Solution:

int lengthOfLongestSubstring(string s) {
    int max = 0, temp = 0, now = 0;
    unordered_map<char, int> c2i;
    for (int  i = 0; i < s.length(); i++){
        if(c2i.count(s[i]) == 0){
            temp++;
            c2i[s[i]] = i;
        }else{
            int t = c2i[s[i]];
            c2i[s[i]] = i;
            for(int j = t-1; j >= now; j--){
                c2i.erase(s[j]);
            }
            if(temp > max){
                max = temp;
            }
            temp -= (t - now);
            now = t + 1;
        }
    }
    max = max > temp ? max : temp;
    return max;
}

PS.

今天的问题只要在于对于map的操作不熟悉,应用的几个操作分别是:

count(KEY):统计某个值出现的次数(0或1因为map不允许出现重复元素);

erase(KEY):抹除某个值的元素。

除此之外查看C++文档:

http://www.cplusplus.com/reference/unordered_map/unordered_map/

PPS.

看到一种更好的写法(JAVA)

public int lengthOfLongestSubstring(String s) {
    int n = s.length();
    Set<Character> set = new HashSet<>();
    int ans = 0, i = 0, j = 0;
    while (i < n && j < n) {
        // try to extend the range [i, j]
        if (!set.contains(s.charAt(j))){
            set.add(s.charAt(j++));
            ans = Math.max(ans, j - i);
        }
        else {
            set.remove(s.charAt(i++));
        }
    }
    return ans;
}

 

posted @ 2018-09-03 21:07  一只狐狸scse  阅读(77)  评论(0)    收藏  举报