题目:max length in leetcode

来源:互联网 发布:棋牌游戏源码可控制 编辑:程序博客网 时间:2024/04/29 01:02

题目

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.

使用MAP来改善查找是否有重复,ldx 与 rdx 分别表示这个sub string 的左边的下标和右边的下标

class Solution {

public:
    int lengthOfLongestSubstring(string s) {
        if (s.size()==0) return 0;
        int max_length = 1;
        map<char,int> imap;
        int ldx = 0;
        int rdx = 0;
        for(;rdx<s.size();++rdx){
            if(imap.find(s[rdx])!=imap.end()){
                int mdx = imap[s[rdx]];
                if(mdx>=ldx){ //考虑这些重复是否有用
                    int len = rdx-ldx;
                    max_length = (len>max_length?len:max_length);
                    ldx = mdx + 1;
                }
            }
            imap[s[rdx]]=rdx;//更新最新的index
        }
        max_length = ((rdx-ldx)>max_length)?(rdx-ldx):max_length;
        return max_length;
    }
};
0 0
原创粉丝点击