美文网首页
longest substring without repeat

longest substring without repeat

作者: wangpancn | 来源:发表于2017-04-19 14:50 被阅读0次

    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.
    Subscribe to see which companies asked this question.
    题目描述如上。
    一开始的想法就是维护start,end分别表示substring with non-repeating characters的起始和结束。但是如何更新以及在什么时候更新这两个变量,没有弄清楚。匆忙写了代码,提交,自然是wrong answer。看了discuss之后,仿照java版的答案,写了C++的版本。
    代码如下。

    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            int maxlen = 0;
            map<char,int> dict;
            for(int i=0,j=0 ; i<s.size() ; ++i )
            {
                if( dict.find(s[i])!=dict.end() )
                {
                    //j=max(j,dict[s[i]]+1);
                    //a case of demo
                    //why we need a max value
                    //abcba
                    if(j<dict[s[i]]+1)
                        j=dict[s[i]]+1;
                }
                dict[s[i]]=i;
                if( maxlen<i-j+1 )
                    maxlen = i-j+1;
                //maxlen = max(maxlen,i-j+1);
            }
            return maxlen;
        }
    };
    

    1.需要注意每次更新j时,都需要将j同dict[s[i]]+1进行比较,选择两者中的较大数,如果仅将j更新成dict[s[i]]+1,而没有进行比较,就不能处理如abcba的情形。

    相关文章

      网友评论

          本文标题:longest substring without repeat

          本文链接:https://www.haomeiwen.com/subject/kixhzttx.html