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

相关推荐

点赞 评论 收藏
分享
01-30 22:03
门头沟学院 Java
用微笑面对困难:我滴妈,【俩月】【实习】【主管】仨debuff吃满了,独立设计开发的项目写了绝大占比的运营板块,你独立开发,那维护、问题复盘、日志更新、bug、策划书全是自己整的? 不建议写那么大,可以从小出发更容易
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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