前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++版- Leetcode 3. Longest Substring Without Repeating Characters解题报告

C++版- Leetcode 3. Longest Substring Without Repeating Characters解题报告

作者头像
Enjoy233
发布2019-03-05 14:35:48
3550
发布2019-03-05 14:35:48
举报

Leetcode 3. Longest Substring Without Repeating Characters

提交网址: https://leetcode.com/problems/longest-substring-without-repeating-characters/

Total Accepted: 149135 Total Submissions: 674678 Difficulty: Medium

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.

分析:

使用哈希表,保存每个字符上一次出现的位置,时间复杂度为O(n).

AC代码:

代码语言:javascript
复制
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int loc[256];     // 哈希表保存字符上一次出现的位置,ASCII码是8位,一般用前7位,是128(2^7)个可用字符。IBM机器的扩展使用了最高位,故用2^8个(256)
        memset(loc, -1, sizeof(loc));
        
        int curStartIdx = -1, max_len = 0;  //curStartIdx为当前子串的开始位置,初始化为-1
        for(int i = 0; i < s.size(); i++)
        {
            if(loc[s[i]] > curStartIdx)  //如果当前字符出现过,那么当前子串的起始位置为这个字符上一次出现的位置+1
            {
                curStartIdx = loc[s[i]];
            }
            if(i - curStartIdx > max_len)  // 使用贪心算法进行子串延伸,关键!!!
            {
                max_len = i - curStartIdx;
            }
            loc[s[i]] = i;  //如果当前字符没出现过,将其位置记录在loc数组中 
        }
        return max_len;
    }
};

You are here!  Your runtime beats 61.72% of cppsubmissions.

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016年05月15日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档