LeetCode Algorithms 3. Longest Substring Without Repeating Characters 题解

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

Examples:

Given “abcabcbb“, the answer is “abc”, which the length is 3.

Given “bbbbb“, the answer is “b”, with the length of 1.

Given “pwwkew“, 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.

题目要求很短,甚至没有限定字符集,但是根据提交代码情况来看,字符串包含的只有ascii码里面的字符。

最先想到的就是暴力解法,设两个index(i,j),i代表开始的字符位置,需要遍历整个字符串,j代表终止字符,从开始字符开始遍历,找到已经出现过的字符后停止,获得子串长度。

有个问题就是如何判断字符已经出现过,可以设置一个子串sub_s,每遍历一个新字符都check该字符是否已经出现在sub_s里面,没有则在子串后加上该字符。

但是这样复杂度就太高了,所以我选择空间换时间的策略,使用一个长度为126(ascii码最后一个是126)的数组,字符的ascii码作为index,初始化为0,已经访问的设置为1,每次终止之后要重新初始化数组为0,这样能省去遍历子串的麻烦。

以下贴出我自己的solution:

int Solution::lengthOfLongestSubstring(string s) {
    if (s.length() == 0) {
        return 0;
    }
    int count = 0;
    int i = 0, j = 0;// i子串头,j子串尾
    int letter[126] = { 0 };// 记录字符是否存在

    while (j < s.length()) {
        if (!(letter[s[j] - 1])) {
            letter[s[j] - 1]++;
        }
        else {
            int sum = j - i;
            count = sum > count ? sum : count;
            i++; // 开始下一个子串遍历
            j = i - 1; // 因为循环结尾要j++,这里加-1为了重置子串尾与头在同一位置
            memset(letter, 0, sizeof(letter));
        }
        if (j == s.length() - 1) {
            return count > s.length() - i ? count : s.length() - i; // s.lenght - 1 - i + 1;
        }
        j++;
    }
}

其余解法待添加

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值