1. 程式人生 > >3. Longest Substring Without Repeating Characters(求最長的不重複的連續的子序列。)

3. Longest Substring Without Repeating Characters(求最長的不重複的連續的子序列。)

官網

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.

題目大意

  • 1.求最長的不重複的連續的子序列。

解題思路

  • 1.如果這個字母重複了,找到它之前的那個位置,那麼從它之前的那個位置的後一個開始計算的話到現在這個位置就不是重複的了。例如:1 2 3 4 3 7 5 6,這裡,3是第一個重複的,找到他之前出現的那個位置的後一個位置即4,這個時候重新開始往後看有事一條好漢了是不是?

AC程式碼

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        //重複了就從之前那個位置的後一個再來
    int
i = 0, j = 0; int visited[256]; int maxlen = 0; fill(visited, visited + 256, 0); while (j < s.length()){ if (visited[s[j]] == 0){ visited[s[j]] = 1; j++; } else{ //如果已經訪問過了,找到它之前訪問過的位置,順便將他之前的一段子序列標記為未訪問,因為下一個起點已經變為k+1了 while
(s[i] != s[j]){ maxlen = max(maxlen, j - i); visited[s[i]] = 0; i++; } //然後從它後一個位置開始訪問,那麼j位置就不是重複的了,就可以繼續向後看了 i++; j++; } } maxlen = max(maxlen, j - i); //cout << maxlen << endl; return maxlen; } };