leetcode3:無重複字元的最長子串
阿新 • • 發佈:2018-11-11
1 題目
給定一個字串,找出不含有重複字元的最長子串的長度。
示例 1:
輸入: “abcabcbb”
輸出: 3
解釋: 無重複字元的最長子串是 “abc”,其長度為 3。
示例 2:
輸入: “bbbbb”
輸出: 1
解釋: 無重複字元的最長子串是 “b”,其長度為 1。
示例 3:
輸入: “pwwkew”
輸出: 3
解釋: 無重複字元的最長子串是 “wke”,其長度為 3。
請注意,答案必須是一個子串,“pwke” 是一個子序列 而不是子串。
題目連結:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
2 解法
2.1 暴力求解法
class Solution { public: int lengthOfLongestSubstring(string s) { int maxlength = 0; for(int i = 0;i < s.size();i++){ string sub(1,s[i]); for (int j = i+1; j < s.size();j++){ if(sub.find(s[j]) == string::npos){ sub.append(1,s[j]); }else{ break; } } if(sub.size() > maxlength){ maxlength = sub.size(); } } return maxlength; } };
2.2 滑動視窗法
class Solution { public: int lengthOfLongestSubstring(string s) { //滑動視窗的方法 int start=0; int end = 0; int maxlength = 0; string sub; for(; end < s.size() && start < s.size(); ){ if(sub.find(s[end]) == string::npos){ //cout<<"if:"<<end<<endl; sub.append(1,s[end]); end++; if(end - start > maxlength){ maxlength = end - start; } }else{ //cout<<"else:"<<sub.size()<<endl; //cout<<"sub:"<<sub<<endl; sub = sub.erase(0,1); start++; } } return maxlength; } };
2.3 優化的滑動視窗法
class Solution {
public:
int lengthOfLongestSubstring(string s) {
//優化的滑動視窗的方法
int start=0;
int end = 0;
int maxlength = 0;
string sub;
int loc;
for(; end < s.size() && start < s.size(); ){
loc = sub.find(s[end]);
if(loc == string::npos){
//cout<<"if:"<<end<<endl;
sub.append(1,s[end]);
end++;
if(end - start > maxlength){
maxlength = end - start;
}
}else{
//cout<<"else:"<<sub.size()<<endl;
//cout<<"sub:"<<sub<<endl;
sub = sub.erase(0,loc+1);
start = start + loc+1;
}
}
return maxlength;
}
};
心得: string型別的相關操作函式不是很熟練,需要加強。