1. 程式人生 > >Longest Substring Without Repeating Character

Longest Substring Without Repeating Character

LeetCode第三題,題目描述:

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.

錯誤的想法:

建立一個子串,遍歷字串的同時,首先判斷當前字元是否在子串中,如果不在,則將其放到子串中;否則,清空子串,同時比較tmpLen與maxLen的大小,如果maxLen小於tmpLen,則用tmpLen替換maxLen,程式碼如下:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int maxLength = 0, tmpLength = 0;
    	int startIndexOfMaxLength = 0, endIndexOfMaxLength = 0;
    	int i;
    	string currentSubStr;
    	int len = s.length();
    	
    	for (i=0; i < len; ++i)
    	{
    		if (string::npos == currentSubStr.find(s[i]))	//如果不存在
    		{
    			currentSubStr.append(1, s[i]);
    			tmpLength ++;
    		}
    		else
    		{
    			if (maxLength < tmpLength)
    			{
    				endIndexOfMaxLength = i;
    				startIndexOfMaxLength = i - currentSubStr.length();
    				maxLength = tmpLength;
    				tmpLength = 1;
    				currentSubStr = currentSubStr.erase(0, currentSubStr.length());
    				currentSubStr.append(1, s[i]);
    			}
    		}
    	}
    	
    	if (maxLength < tmpLength)
	    	maxLength = tmpLength;
    	
    	return maxLength;
    }
};
這種做法是錯誤的,因為忽略這了這樣一種情況:
Input: "dvdf"
Output: 2
Expected: 3

目前思路是:

在當前已知的最大長度的子串中,查詢到第一個重複的字元,然後再從該字元處查詢,直到查詢到第二個重複