笔试题16. LettCode OJ (3)

3. Longest Substring Without Repeating Characters

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.

题目意思是找出一段字符串序列中的最长的无重复字符的子串的长度

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if(s.size() < 1)
        {
            return 0;
        }
        int maxlen = 0;
        int begin=0;  //从begin到i的字符串中若有重复就将begin前进一位
        for(int i=0; i < s.size(); ++i)
        {
            if(isnotrepeat(s, s[i], begin, i))
            {
                if(i-begin+1 > maxlen)
                { //判断目前无重复串的长度是不是最长的,若是则用maxlen记录它
                    maxlen = i-begin+1;
                }
            }
            else
            {
                while(!isnotrepeat(s,s[i],begin,i))
                { //一直处理,直到下标从begin到i的字符串中无重复字符串为止
                    begin++;    
                }
            }
        }
        return maxlen;
    }
    
    bool isnotrepeat(string s,char c, int begin,int end)
    { //判断一个字符串序列中是否和目标字符c重复的
        for(int i=begin; i<end; ++i)
        {
            if(s[i] == c)
            {
                return false;
            }
        }
        return true;
    }
};


你可能感兴趣的:(笔试题16. LettCode OJ (3))