3. Longest Substring Without Repeating Characters

题目描述:

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.

思路:滑动窗口。

程序:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        string s1;
        int longest = 0;
        for (int i = 0; i < s.size(); i++)
        {
            string::iterator it = find(s1.begin(), s1.end(), s[i]);
            if(it != s1.end())
            {
                s1.erase(s1.begin(),it + 1);
            }
            s1 += s[i];
            if (s1.size() > longest)
            {
                longest = s1.size();
            }
        }
        return longest;
    }
};

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

你可能感兴趣的:(Leetcode刷题之旅)