首页 > 其他 > 详细

LeetCode 003. Longest Substring Without Repeating

时间:2015-05-20 02:16:54      阅读:275      评论:0      收藏:0      [点我收藏+]

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.

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

写了一些臆想的代码:

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;
}




LeetCode 003. Longest Substring Without Repeating

原文:http://my.oschina.net/u/347565/blog/417045

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!