leetcode_c++:哈希:Longest Substring Without Repeating Characters(003)

来源:互联网 发布:怎样做淘宝详情页 编辑:程序博客网 时间:2024/05/16 05:17

题目

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
O(N)

  • 申请数组,记录当前字符出现的最近位置,一遍算过去,更新左边界,利用最边界计算;

const int N = 300;class Solution {public:    int lengthOfLongestSubstring(string s) {        int maxlen = 0,left = 0;        int sz = s.length();        int prev[N];        memset(prev,-1,sizeof(prev));        for(int i=0;i<sz;i++){            if(prev[s[i]]>=left)                left=prev[s[i]]+1;            prev[s[i]] = i;            maxlen = max(maxlen,i-left+1);                  }        return maxlen;    }};
0 0
原创粉丝点击