leetcode-----------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.

点击这个链接你可以看到更多的解决方法:https://oj.leetcode.com/discuss/6168/my-o-n-solution

下面是我自己的方法,在线AC通过。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int max = 0;
        
        // 记录子串起始位置的前一个位置的下标
        // 初始化为-1
        int idx = -1;
        
        // 记录字符在s中出现的位置
        int locs[256];
        memset(locs, -1, sizeof(int) * 256);
        for (int i = 0; i < s.size(); i++) {
            // 如果s[i]在当前子串中出现过
            if (locs[s[i]] > idx) {
                // 新子串的起始位置设为s[i]出现的位置+1
                // P.S. idx是记录起始位置的前一个位置的下标
                idx = locs[s[i]];
            }
            // 如果当前子串的长度大于最大值
            if (i - idx > max) {
                max = i - idx;
            }
            // 更新字符s[i]出现的位置
            locs[s[i]] = i;
        }
        return max;
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值