码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 003. Longest Substring Without Repeating

时间:2015-05-20 02:18:57      阅读:100      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!