LeetCodeの問題はLongest Substring Without Repeating Chracters(O(n)アルゴリズム)の問題を解決します.


problem:
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.
thinking:
(1)串を探して、一度作ってみます.
(2)暴力解読法は、各サブストリングを確認し、hash tableのマッピング思想を利用して、配列を作り、文字として表示されたASCIIコードを下に表示します.文字列の種類を説明していないので、hash tableのサイズを圧縮するための措置を講じることができます.暴力解読法の最悪時間複雑度はO(n*n)である.
(3)O(n)のアルゴリズムを見つけました.いいですね.
実は、ここの多くの仕事は重複していて、無用です.一例を見ると、S="abdeca"です.t 1=「abdeca」、t 1[1]==t 1[2]t 2=「bbdeca」、t 2[0]==t 2[1]t 3=「bdeca」は最後までスキャンします.t 4=「deca」、t 5、t 6、t 7は同じです.私たちはt 1を処理する時にs[2]までスキャンしました.そしてt 3を処理する時にs[2]からs[6]までスキャンしました.すなわち、サブストリングを停止させることができる位置は、2つだけである.2.s[6](末尾)他の例S=「aaaab」に対して、サブストリングを停止させることができる位置は、それぞれs[1],s[2],s[3](末尾)である.したがって、母ストリングだけをスキャンして、直接に母ストリングから最長の重複なしのサブストリングを取り出すことが考えられます.s[i]:1.s[i]は現在のサブストリングに現れていないので、サブストリングの長さを1とする.2.s[i]は現在のサブストリングにおいて出現したことがあり、出現位置の下がjと表記されている場合、新しいサブストリングの開始位置はjより大きくなければならず、新しいサブストリングをできるだけ長くするために、開始位置はj+1と選択される.
コード:
説明:注釈の解法は複雑度がO(n*n)で、コメントのないビットO(n)
#include <iostream>
#include <string>
#include <memory.h>

using namespace std;
/*
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int a[100]; //  hash table
        memset(a,0,sizeof(int)*100);
        int length = s.size();
        int index=0;
        int max=0;
        for(int i=0;i<length;i++)
        {
            int j=i;
            while((j<length)&&(a[s.at(j)-32]==0))//  hash table
            {
                a[s.at(j)-32]=1;
                index++;
                j++;
            }
            memset(a,0,sizeof(int)*100);
            max=(max>index)?max:index;
            index=0;
            if(j==length-1) //         ,           
                break;
        }
        return max;
    }
};
*/
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int locs[256];//            
        memset(locs, -1, sizeof(locs));

        int idx = -1, max = 0;//idx          -1
        for (int i = 0; i < s.size(); i++)
        {
            if (locs[s[i]] > idx)//         ,                        +1
            {
                idx = locs[s[i]];
            }

            if (i - idx > max)//     !!!!!!!!!
            {
                max = i - idx;
            }

            locs[s[i]] = i;
        }
        return max;
    }
};
int main()
{
    string str = "abcdab";
    Solution mysolution;
    cout<<mysolution.lengthOfLongestSubstring(str)<<endl;

}