Longest Substring Without Repeating Characters —— Leetcode

来源:互联网 发布:有线网络电视怎么连接 编辑:程序博客网 时间:2024/06/06 07:39

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

哈希表和滑动窗口解决重复字符的问题。

这题与其说是动态规划,不如说用滑动窗口来解决,维护begin、end和len三个变量来记录窗口的起始位置、终止位置和长度,维护一个256大小的hashtable来记录一个字符最近一次出现过的位置,具体代码如下:

class Solution {public:    int lengthOfLongestSubstring(string s) {                vector<int> arr(256, -1);        int begin=0, len=0, longest=0;        for(int end=0; end<s.size(); end++) {            if(arr[s[end]] >= 0) {                begin = max(begin, arr[s[end]] + 1);            }            len = end - begin + 1;            longest = max(longest, len);                        arr[s[end]] = end;        }        return longest;    }};


0 0
原创粉丝点击