[leetcode] 3.Longest Substring Without Repeating Characters

题目:
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.
题意:
给定一个字符串,找出字符串中最长的子串的长度,该子串中所有字符不重复。
思路:
依旧使用两个指针,初始化的时候两个指针都指向第一个字符,然后使用表记录所遇到的字符出现的下标,如果第二个指针扫描到字符s[i]已经在表中出现过了,那么记录此时的子串的长度。让第一个指针往前走,走到表中s[i]字符对应的下标。并且第一个指针往前走的过程中,扫描到的字符需要在表中去掉位置信息,相当于“出栈”了,告诉第二个指针这些字符没出现过。

代码如下:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if (s.empty())return 0;
        int table[256];
        memset(table, -1, sizeof(table));
        int first = 0, second = 0, length = s.length();
        int m = 0;
        while (second < length) {
            if (table[s[second]] == -1) {
                table[s[second]] = second;
            }
            else {
                m = max(m, second - first);
                while (first <= table[s[second]]) {
                    table[s[first]] = -1;
                    first++;
                }
                table[s[second]] = second;
            }
            second++;
        }
        m = max(m, second - first);
        return m;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值