LeetCode 003. Longest Substring Without Repeating

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. spa

看错题了,题目要求找出字符串中的一个最长的子串,使得这个子串不包含重复的字符,这个子串的长度。当作了找出一个最长重复子串,它不包含重复的字符。题目给的两个例子也刚好符合个人臆想,想一想也是醉了。 code

写了一些臆想的代码: orm

unordered_set<char> tmp;
bool is_unique(string& s)
{
    tmp.clear();
    for(int i=0; i!= s.size(); ++i)
    {
        if(tmp.find(s[i]) != tmp.end())
            return false;
        tmp.insert(s[i]);
    }
    return true;
}

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        unordered_set<string> allsubstrings;
        int maxlength = 1;
        int i, j;
        string str;
        for(i=0; i!= s.size(); ++i)
        {
            for(j =i+maxlength; j<= s.size(); ++j)
            {
                str = s.substr(i,j-i);
                if(is_unique(str))
                {
                    if(allsubstrings.find(str) != allsubstrings.end())
                    {
                        if(maxlength < str.size())
                            maxlength = str.size();
                    }
                    else
                    {
                        allsubstrings.insert(str);
                    }
                }
                else
                {
                    break;
                }
            }
        }
        return maxlength;
    }
};
原题的解:

int lengthOfLongestSubstring(string s) {
  int n = s.length();
  int i = 0, j = 0;
  int maxLen = 0;
  bool exist[256] = { false };
  while (j < n) {
    if (exist[s[j]]) {
      maxLen = max(maxLen, j-i);
      while (s[i] != s[j]) {
        exist[s[i]] = false;
        i++;
      }
      i++;
      j++;
    } else {
      exist[s[j]] = true;
      j++;
    }
  }
  maxLen = max(maxLen, n-i);
  return maxLen;
}
相关文章
相关标签/搜索