Longest Substring Without Repeat
2019-06-17 本文已影响0人
Aptitude
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) {
if(s.empty())
return 0;
int i,maxLength = 0;
string temp;
for(i=0;i<strlen(s.c_str());i++){
if(temp.find(s[i]!=temp.npos)){
temp = temp.substr(temp.find(s[i])+1,strlen(temp.c_str()));
}
temp = temp + s[i];
maxLength = max(maxLength,strlen(temp.c_str()));
}
return maxLength;
}
int max(int a,int b){
return a>b?a:b;
}
};