【LeetCode】3. Longest Substring Without Repeating Characters

题目:

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.

描述:

给出一个字符串,求最长不重复字符的子串(子串是必须连续的!)的长度。

分析:

用尺缩法....

维护一个数组,来标识某字符是否出现过,随后向后继续遍历,尝试增大不重复子串的长度,并使用length标识的当前所维护串的长度,若某字符已出现过,则从左向右缩短所维护串的长度,直到子串不包含重复的字符,依此运行到字符串遍历结束,在整个过程中,记录length所能达到的最大长度,即为所得。

该算法的时间复杂度O(n),由于只使用了一个容量为256的数组,因此空间复杂度为O(1)。

该题的坑点:

测试数据中会出现除小写字母以外的字符!!!!!!!

所以辅助数组应为拓展ASCII码的最大范围256....

 

代码:

class Solution {
public:
int lengthOfLongestSubstring(string s) {
        int length = 0, result = 0, left = 0;
		int temp[256] = {0};
        for (int i = 0; i < s.size(); ++ i) {
        	int right = s.at(i);
        	if (!temp[right]) {//如果某字符未出现过 
        		++ temp[right];
				length += 1;
				if (length > result) {
					result = length;
				}
			} else {//若某字符第二次出现
				++ length; 
				++ temp[right];//将第二次出现的位置累加 
				for (int j = i - length + 1; j < i; ++j) {//从左往右缩短,直到不出现重复的字母
					-- length;
					int left = s.at(j);
					-- temp[left];
					if (temp[left]) {//说明已经缩到无重复字母的最左侧
						break; 
					}
				}
			}
		}
		return result;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值