1. 程式人生 > >字串+雜湊表+小動態規劃(Longest Substring Without Repeating Characters -- LeetCode)

字串+雜湊表+小動態規劃(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後移一位。


#include<iostream> 
#include<string.h>
#include<algorithm>
#include<math.h>
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<<s.lengthOfLongestSubstring(str)<<endl;
return 0;
}