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

来源:互联网 发布:java ftp 编辑:程序博客网 时间:2024/04/28 15:26

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

  • LeetCode 3 Longest Substring Without Repeating Characters线性处理 哈希
    • 问题描述
    • 解题思路
    • 参考代码

  • By Scarb
  • Scarb’s Blog

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
原创粉丝点击