给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
class Solution {
public: int lengthOfLongestSubstring(string s) {
int ret = 1, me = 1; int sz = s.size(); if(sz == 0) return 0; for(int i = 0, k = i + 1; k < sz; ) for( ; k < sz; k++){
int here = find(s.begin() + i, s.begin() + k, s[k]) - s.begin(); if(here == k) me++; else if(here == k - 1){
ret = max(ret, me); i = k++; me = 1; break; } else {
ret = max(ret, me); i = here + 1; me = ++k - i; break; } } ret = max(ret, me); return ret; } };
hashmap解法
class Solution {
public: int lengthOfLongestSubstring(string s) {
//s[start,end) 前面包含 后面不包含 int start(0), end(0), length(0), result(0); int sSize = int(s.size()); unordered_map<char, int> hash; while (end < sSize) {
char tmpChar = s[end]; //仅当s[start,end) 中存在s[end]时更新start if (hash.find(tmpChar) != hash.end() && hash[tmpChar] >= start) {
start = hash[tmpChar] + 1; length = end - start; } hash[tmpChar] = end; end++; length++; result = max(result, length); } return result; } }; 作者:pinku-2 链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/solution/wu-zhong-fu-zi-fu-de-zui-chang-zi-chuan-cshi-xian-/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
桶优化
class Solution {
public: int lengthOfLongestSubstring(string s) {
//s[start,end) 前面包含 后面不包含 int start(0), end(0), length(0), result(0); int sSize = int(s.size()); vector<int> vec(128, -1); while (end < sSize) {
char tmpChar = s[end]; //仅当s[start,end) 中存在s[end]时更新start if (vec[int(tmpChar)] >= start) {
start = vec[int(tmpChar)] + 1; length = end - start; } vec[int(tmpChar)] = end; end++; length++; result = max(result, length); } return result; } }; 作者:pinku-2 链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/solution/wu-zhong-fu-zi-fu-de-zui-chang-zi-chuan-cshi-xian-/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。