字符串+哈希表+小动态规划(Longest Substring Without Repeating Characters -- LeetCode)

Longest Substring Without Repeating Characters

题目难度:3   面试频率 2  . (1-5)

题目描述:

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.

链接:http://oj.leetcode.com/problems/longest-substring-without-repeating-characters/

题意:找出字符串的最长不重复子串。

分析:

1.暴力枚举时间复杂度为o(n^3),先找出所有子串,再判断每个子串中是否有重复字符,一般情况都不会这样做。

2.哈希表可以实现快速查找,对于本题,创建一个哈希表(用来存储字符的位置),初始化时表中每个数据赋值为-1,定义两个指针start和end,用于记录当前子串开始的位置和正在考察是否重复字符的位置。当end位置的字符用hash表判断出之前有重复字符时,start的位置后移(注意后移不一定只移一位,而是移动到end位置的下一位),同时end位置后移一位继续判断,否则satrt位置不动,end后移一位。

字符串+哈希表+小动态规划(Longest Substring Without Repeating Characters -- LeetCode)_第1张图片

#include 
#include
#include
#include
using namespace std;
int Max(int a,int b){
return a>b?a:b;
}
class Solution{
public:
/*法一 
int lengthOfLongestSubstring(string s){
int hash[256];
for(int i = 0; i < 256; i++){
hash[i] = -1;
}
int start = 0,ans = 0;
int i;
for(i = 0; i < s.size(); i++){
if(-1 != hash[s[i]]){
if(ans < i-start)ans = i-start;
for(int j = start; j<< hash[s[i]]; j++)hash[j] = -1;
if(hash[s[i]] + 1 > start)
start = hash[s[i]] + 1;
}
hash[s[i]] = i;
}
if(ans < i-start) ans = i-start;
return ans;
}*/
/*法二 
int lengthOfLongestSubstring(string s) {
    int max = 0, start = 0;
    bool exist[26];
    int position[26];
 
    for(int i = 0; i < 26; i++) {
        exist[i] = false;
        position[i] = 0;
    }
 
    for(int i = 0; i < s.size(); i++) {
        if(exist[s[i] - 'a']) {
            for(int j = start; j <= position[s[i] - 'a']; j++) {
                exist[s[j] - 'a'] = false;
            }
            start = position[s[i] - 'a'] + 1;
            exist[s[i] - 'a'] = true;
            position[s[i] - 'a'] = i;
        }
        else {
            exist[s[i] - 'a'] = true;
            position[s[i] - 'a'] = i;
            max = max > (i - start + 1) ? max : (i - start + 1);
        }
    }
 
    return max;*/
    //法三 
    int lengthOfLongestSubstring(string s){
    int hash[256];
    memset(hash,-1,sizeof(int)*256);
    int len = s.length();
    int start = 0,end = 1;
    int max = 1;
    hash[s[0]] = 0;
    while(end < len){
    if(hash[s[end]] >= start){
    start = hash[s[end]]+1;
}
max = Max(max,end-start+1);
hash[s[end]] = end;
end++;
}
return max;
}

}; 


int main(){
string str = "abbcdefh";
Solution s;
cout<return 0;
}


你可能感兴趣的:(ACM—字符串)