LeetCode笔记-A3-Longest Substring Without Repeating Characters

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

Examples:

Given “abcabcbb”, the answer is “abc”, which the length is 3.

Given “bbbbb”, the answer is “b”, with the length of 1.

Given “pwwkew”, the answer is “wke”, with the length of 3. Note that the answer must be a substring, “pwke” is a subsequence and not a substring.

MySolution:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if (s.length()==0) {
            return 0;
        }
        else if (s.length()==1) {
            return 1;
        }
        else{
            int max=0;
            for (int i = 0; i < s.length(); ++i) {
                int len = LongestWithAlpha(s.substr(i,s.length()));
                if (len>max) {
                    max=len;
                }
            }
            return max;
        }

    }
    //check if the string s contains duplicate character
    int LongestWithAlpha(string s){
        int length=1;
        for (int i = 1; i < s.length(); ++i) {
            if (!isInStr(s.substr(0,i),s[i])) {
                length++;
            }else break;
        }
        return length;

    }
    bool isInStr(string s,char a){
        string::size_type idx = s.find( a );

        if ( idx != string::npos )
        {
            return true;
        }

        return false;
    }
};

总结:非常暴力的写法,速度果然也是最慢的一档QAQ
思路很简单,从第一个字母开始找最长的无重复字母的子串,一旦发生重复,就记录这个长度,然后从第二个字母开始重复上述过程。如果标准库里的find复杂度是O(n)的话,整个过程的时间复杂度是O(n^3)。写完之后就发现其实不需要从第二个字母开始,从被发现重复的字母之后的一个字母开始就可以了,比如abcdefcg,发现了重复的”c”,这时候从d开始重复上述步骤就好了,复杂度可以降到O(n^2)。不过写的时候,正在做饭,而且代码写得有点死,就懒得改了QAQ。
官方给出的解法是用hashmap让查找复杂度变成O(1),然后根据上面的思路只扫描了一遍字符串,有一点点tricky:

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length(), ans = 0;
        Map<Character, Integer> map = new HashMap<>(); // current index of character
        // try to extend the range [i, j]
        for (int j = 0, i = 0; j < n; j++) {
            if (map.containsKey(s.charAt(j))) {
                i = Math.max(map.get(s.charAt(j)), i);
            }
            ans = Math.max(ans, j - i + 1);
            map.put(s.charAt(j), j + 1);
        }
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/ken_for_learning/article/details/81736400