LeetCode 3. Longest Substring Without Repeating Characters(线性处理, 哈希)

LeetCode 3. Longest Substring Without Repeating Characters(线性处理, 哈希)

Tags:
- Hash Table
- Two Pointers
- String

问题描述

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.

解题思路

  • 先定义一个dict,用来存储所有字符最后出现的位置,初始化为-1.
  • 再设置begin变量,用以记录当前没有重复字符子串的起始位置,初始化为0。
  • max_len为最大长度,初始为0.

    1. 从左到右扫描字符串,读入每一位字符。当该位字符上一次出现的位置在begin之后,说明该字符重复。比较此时的字符串长度是否最长,如果是最长则赋给max_len
    2. 然后将begin移动到上一个重复字符的下标+1的位置(这样可以保证begin到当前下标都没有重复),继续向后扫描。
    3. 最后返回max_len,此时还要将begin到字符串末的长度再与max_len对比,因为最后一次没有比。

参考代码

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        vector<int> dict(256, -1);          // ACSII_MAX = 256, means last pos of this repeating character
        int max_len = 0;                    // longest substring len
        int begin = 0;                      // begin index

        for (int i = 0; i < s.size(); ++i)
        {
            if (dict[s[i]] >= begin)
            {
                max_len = max(i - begin, max_len);
                begin = dict[s[i]] + 1;
            }
            dict[s[i]] = i;
        }
        return max((int)s.size() - begin, max_len);
    }
};

int main()
{
    string str = "abcabcbb";
    auto sl = new Solution();
    cout << sl->lengthOfLongestSubstring(str) << endl;

    system("pause");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值