Leetcode 3. 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.

方法一:時間複雜度爲O(n2),每次遍歷一個查看前面有麼有與之相同的的字母,若有相同字母則把初始位置設在那個相同字母后面的位置。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if(s.empty())
            return 0;
        int i=0,j,count=0,max=0;
        for(j=0;j<s.size();j++){
            for(int k=i;k<j;k++)
                if(s[k]==s[j]){
                    count=j-i;
                    max=count>max?count:max;
                    i=k+1;
                    break;
                }
        }
        count=j-i;
        max=count>max?count:max;
        return max;
    }
};

方法二:犧牲空間的方法去,提高搜索時間效率,時間複雜度O(n)。類似於關聯數組,map。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int locs[256];
        memset(locs, -1, sizeof(locs));

        int idx = -1, max = 0;
        for (int i = 0; i < s.size(); i++)
        {
            if (locs[s[i]] > idx)
            {
                idx = locs[s[i]];
            }

            if (i - idx > max)
            {
                max = i - idx;
            }

            locs[s[i]] = i;
        }
        return max;
    }
};




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章