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;
    }
};
全部评论

相关推荐

02-08 15:53
门头沟学院 Java
CoderEcho:让公司知道便宜没好货
点赞 评论 收藏
分享
Aki-Tomoya:窝趣,人家这是先富带动后富,共同富裕了属于是
投递英伟达等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务