LeeCode: 3. Longest Substring Without Repeating Characters

LeeCode: 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.

解题思路 —— Hash

利用 hash 表标记各个字母最近出现的位置,当出现重复字母时,将其对应的位置设为当前位置。

AC 代码

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int hash[256] = { 0 }; // 标记连续出现过的字母最近出现的位置
        int ans = 0, cnt = 0;
        int flag = 0; // 记录当前连续序列的起始位置

        for(size_t i = 0; i <= s.size(); ++i)
        {
            if(i == s.size())
            {
                if(ans < cnt) ans = cnt;
                break;
            }

            if(hash[s[i]] > flag){
                if(ans < cnt) 
                {
                    ans = cnt;
                }
                cnt = i - hash[s[i]];
                flag = hash[s[i]];
            }
            ++cnt;
            hash[s[i]] = i+1;
        }

        return ans;
    }
};
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-01 17:13
想去,但是听说加班强度实在难崩,所以拒绝了,现在有点心梗对面hr感觉也是实习生,打电话的时候怪紧张的,但是感觉人很好嘞
水中水之下水道的鼠鼠:哥们这不先去体验一下,不行再跑呗,大不了混个实习经历(有更好的转正offer就当我没说)
点赞 评论 收藏
分享
每晚夜里独自颤抖:把华北改为华南再试一试,应该就没啥问题了。改完可能都不用投,别人主动联系了。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务