longest-substring-without-repeating-characters

来源:互联网 发布:美国驾照在中国 知乎 编辑:程序博客网 时间:2024/05/16 01:01

题目:

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) {        int max = 0;        for (int i = 0; i < s.size(); i++)            for (int j = i; j < s.size(); j++)            {                if (isQualified(s.substr(i, j-i+1)))                {                    if(j-i+1>max)                        max = j - i+1;                }                else                    break;//若前面不满足,后面也不会满足,需要及时终止循环,否则会超时            }        return max;    }    bool isQualified(string s)    {        if (s.size() == 1)            return true;        sort(s.begin(), s.end());        for (int i = 0; i < s.size(); i++)        {            if (s[i] == s[i + 1])                return false;        }        return true;    }};