LeetCode 3. Longest Substring Without Repeating Characters(最长不重复连续子串)

题目描述:

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


例子:

Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given Given "abcabcbb", the answer is "abc", which the length is 3.


分析:

   题意:给定一个字符串,找到最长的不重复连续子串并返回长度。
  思路:考察双指针法C++ set应用。我们用指针left,right分别表示需要查找子串的开始、结束位置,初始值均为0且按顺序遍历。①如果s[right]在set中出现,表明已经出现重复字符,此时s[left→right-1]为不重复字串,更新答案,从set中移除s[left],left加1(因为以left开始的最长不重复子串已经找到,left必须更新)。如果s[right]在set中没出现,那么在set中加入s[right]、right加1,继续考察,如果right等于n,说明查找结束了,同时更新一次答案,最后返回最长长度。假设字符串长度为n,时间复杂度为O(n)。

代码:

#include <bits/stdc++.h>

using namespace std;

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int n = s.length();
		// Exceptional Case: 
		if(n == 0){
			return 0;
		}
		int left = 0, right = 0, ans = 0;
		set<char> ss;
		while(left <= right && right <= n - 1){
			// debug
			// cout << "l: " << left << ", r: " << right << endl;
			if(ss.count(s[right])){
				ans = max(ans, right - left);
				ss.erase(s[left]);
				left++;
			}
			else{
				ss.insert(s[right]);
				right++;
				if(right == n){
					ans = max(ans, n - left);
				}
			}
		}
		return ans;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值