LeetCode OJ : 3 Longest Substring Without Repeating Characters

readyao發表於2015-11-27

Longest Substring Without Repeating Characters My Submissions Question

Total Accepted: 109306 Total Submissions: 524897 Difficulty: Medium
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.


class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        vector<string> substrs;
        string str;
        
        for(int i = 0; i < s.size(); ++i){ 
            if(str.find(s[i]) == string::npos){ 
                str.push_back(s[i]);
            }
            else{
                substrs.push_back(str);
                str.clear();
                i = substrs.size()-1;    //從這個重複的字元處開始再次向後查詢
            }
            
            if(i == s.size()-1){         //考慮到一個字串中的字元全部都不相同的情況
                substrs.push_back(str);
            }
        }
        
        int maxlen = 0;
        for(int i = 0; i < substrs.size(); ++i){
            if(substrs[i].size() > maxlen){
                maxlen = substrs[i].size();
            }
        }
        return maxlen;
    }
};


這個思路很簡單,但是時間複雜度太高;



相關文章