LeetCode3. No repeat characters maximum substring

Given a string, you find out which does not contain a sub-length of the longest string of repeated characters.

Example 1:

Input: "abcabcbb"
Output: 3
Explanation: Because the longest substring of characters without repetition is "abc", so its length is 3.
Example 2:

Input: "bbbbb"
Output: 1
Explanation: Because the longest substring is repeated characters without "b", so that its length is 1.
Example 3:

Input: "pwwkew"
Output: 3
Explanation: Because the longest sub-string is repeated characters without "wke", so its length is 3.
  Please note that your answer must be a substring of length, "pwke" is a sub-sequence, not a substring.

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/longest-substring-without-repeating-characters
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if(s=="") return 0;
        int sum=0,res=0;
        string bef="";
        for(int i=0;i<s.length();i++){
            if(bef.find(s[i])==bef.npos) {
                sum++;
                bef+=s[i];
            }
            else{
                int a=bef.find(s[i]);
                bef=bef.substr(a+1,bef.length()-a-1);
                sum=bef.length()+1;
                bef+=s[i];
            }
            if(sum>res) res=sum;
        }
        return res;
    }
};

 

Guess you like

Origin www.cnblogs.com/littlepage/p/11582161.html