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

相关推荐

程序员花海:实习和校招简历正确格式应该是教育背景+实习+项目经历+个人评价 其中项目经历注意要体现业务 实习经历里面的业务更是要自圆其说 简历模板尽可能保持干净整洁 不要太花哨的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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