LeetCode 3. Longest Substring Without Repeating Characters

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

Example 1:

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

Example 2:

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

Example 3:

Input: s = "pwwkew"
Output: 3

Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.

Example 4:

Input: s = ""
Output: 0

Constraints:

0 <= s.length <= 5 * 104
s consists of English letters, digits, symbols and spaces.

实现思路:

题意是找到一个串中字符不重复的最大字串(不包括串本身),和KMP算法的题目看起来很相似,但KMP的应用常用于在一个文本串 S 内查找一个模式串 P 的出现位置,本题可以借鉴KMP的滑动窗口模式,这种滑动窗口模式在字符串题型中非常常见。

AC代码:

class Solution {
	public:
		int lengthOfLongestSubstring(string s) {
			int maxLen=0,cnt=0;
			string temp;
			for(int i=0; i<s.length(); i++) {
				if(temp.find(s[i])==string::npos) {
					temp+=s[i];//找不到当前窗口的字母则添加
				} else {
					if(temp.size()>maxLen) maxLen=temp.size();
					temp=temp.substr(1);//遇到重复情况了例如dvcd 此时temp="dvc"所以截取temp="vc"即可
					i--;//重新滑动窗口到原来重复的窗口位置进行添加
				}
			}
			if(temp.size()>maxLen) maxLen=temp.size();//这是考虑只有一个窗口或者最后一个不重复窗口的情况
			return maxLen;
		}
};


posted @ 2021-02-27 17:35  coderJ_ONE  阅读(49)  评论(0编辑  收藏  举报