无重复字符的最长子串
-
给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串的长度。
-
示例 1:
输入: s = "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
-
示例 2:
-
输入: s = "bbbbb" 输出: 1 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
-
示例 3:
-
输入: s = "pwwkew" 输出: 3 解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。 请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
-
提示:
-
0 <= s.length <= 5 * 104 s 由英文字母、数字、符号和空格组成。
方法一:
#include <iostream>
#include <vector>
#include <sstream>
#include <string>
#include <unordered_map>
using namespace std;
//暴力求解,时间复杂度On^2
// vector<int> twoSum(vector<int>& nums, int target) {
// vector<int> result;
// int n = nums.size();
// for(int i = 0; i < n; ++i){
// for(int j = i+1; j < n; ++j){
// if(nums[i] + nums[j] == target){
// result.push_back(i);
// result.push_back(j);
// }
// }
// }
// return result;
// }
//哈希表,空间换时间
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;//存储数字下标
int n = nums.size();//计算数组长度
unordered_map <int, int> num_map;//存储已访问的元素及下标
for(int i = 0; i < n; ++i){
int complement = target - nums[i];//计算目标值与当前元素的差值
if(num_map.find(complement) != num_map.end()){
// 如果差值已经存在于哈希表中,说明找到了两个数
result.push_back(num_map[complement]);
result.push_back(i);
return result;
}
// 如果没有找到,记录当前元素和它的下标
num_map[nums[i]] = i;
}
return result;
}
int main() {
//输入数组
int target;
cin >> target;
cin.ignore();
string str;
vector<int> ratings;
getline(cin,str);
stringstream ss(str);
string temp;
while(getline(ss, temp, ',')){
ratings.push_back(stoi(temp));
}
vector<int> result = twoSum(ratings, target);
cout << "[" << result[0] << "," << result[1] << "]" << endl;
return 0;
}
方法二:
int lengthOfLongestSubstring(string str){
unordered_set<char> charSet; // 用哈希集合存储当前窗口的字符
int left = 0; // 左指针
int maxlength = 0;// 最大子串长度
for(int right = 0; right < str.size(); ++right){
// 如果右指针所指向的字符已经在窗口中出现过
while(charSet.find(str[right]) != charSet.end()){
// 移动左指针缩小窗口,直到窗口中没有重复字符
charSet.erase(str[left]);
++left;
}
// 将右指针所指向的字符加入窗口
charSet.insert(str[right]);
//更新最大长度
maxlength = max(maxlength,right-left+1);
}
return maxlength;
}
int main(){
string str;
getline(cin,str);
int result = lengthOfLongestSubstring(str);
cout << result << endl;
return 0;
}