LeetCode3. Longest Substring Without Repeating Characters(C++)

Given a string, find the length of the longest substring without repeating characters.

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is"b", with the length of 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: 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.

题目大意:寻找最长的无重复字母的子字符串;

解题思路:双指针法i,j,用j指针进行遍历,利用字母的ASCII码值进行映射,记录是否访问过,如果访问到之前访问过的,则i指针前移,一直遍历到与j指针相同的字母的后,同时修改i遍历过的字母对应的visit数组的值。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int resultmax=0,i=0,j=0;
        bool visit[256]={false};
        while(j<s.length()){
            if(visit[s[j]]==false){
               visit[s[j]]=true;
            }
            else{
                resultmax=max(resultmax,j-i);
                while(s[i]!=s[j]){
                    visit[s[i]]=false;
                    i++;
                }
                i++;
            }
            j++;
        }
        resultmax=max(resultmax,j-i);
        return resultmax;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_41562704/article/details/85367182