[LeetCode]3 Longest Substring Without Repeating Characters (C++,Python实现)

LeetCode OJ的第三题,如果有问题或者给我指点欢迎来信讨论ms08.shiroh@gmail.com

题目描述

Given a string, find the length of the longest substring without repeating characters. 
For example, the longest substring without repeating letters for "abcabcbb" is "abc", 
which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
给定一个字符串,寻找满足其中不存在重复字母的最大的子串的长度。

思路

这题思路较为简单,遍历一遍,判断寻找当前的子字符串是否存在重复的字母即可。如果发现重复的字母重新寻找新的字符串。可以改进的地方在于如何使得其中的过程尽可能少,尽可能快。如果每次发现了重复仅仅把开始的位置向后挪一位,那么就有很多是重复判断了,正确应该是把新子字符串开始的位置移到重复的字母(有前面以及后来重复的两个位置)的前面位置的下一个位置。
过程中涉及查找,就联想到使用字典。
利用map(C++)或者dict(Python)时候,可以利用映射记录该字符串起始的位置,这样就省略了记录长度的过程。用数组也能够解决问题。
注意字符串中不仅仅包含字母,还包含其它的符号,而且大小写字母不算同一个字符。

代码

Python
def lengthOfLongestSubstring(self, s):
        if not s:
            return 0
        dict = [-1 for i in range(256)]
        # mark current substring, value is the index before start place
        current_substring = 0
        longest_length = -1
        for i in range(len(s)):
            index = ord(s[i])
            if dict[index] >= current_substring:
                longest_length = max(longest_length, i-current_substring)
                current_substring = dict[index] + 1
            dict[index] = i
        longest_length = max(longest_length, len(s)-current_substring)
        return longest_length

C++
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
	if (s.size() == 0)
	    return 0;
        int longest_length = 0;
	int dict[256];
	for (int i = 0; i < 256; ++i)
	    dict[i] = -1;
	int current_start = 0;
	for (int i = 0; i < s.size(); ++i) {
	    int index = int(s[i]);
	    // 如果当前的符号上一次出现的位置dict[index]大等于这次子字符串的起始位置
	    // 则说明这次的字符串内出现了重复的符号
	    // 这时候要把其实位置移到冲突符号(有前后两个位置)前面那个的下一个位置
	    if (dict[index] >= current_start) {
		if (i - current_start > longest_length)
			longest_length = i - current_start;
		current_start = dict[index] + 1;
	    }
	    // dict[index]记录该符号这次出现的位置
	    dict[index] = i;
	}
	if (s.size() - current_start > longest_length)
	    longest_length = s.size() - current_start;
	return longest_length;
    }
};




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值