1. 程式人生 > >LeetCode刷題總結#3無重複字元的最長子串

LeetCode刷題總結#3無重複字元的最長子串

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.

分析:
我的想法是使用三個值front、back和mid分別指向子串的頭尾和中間進行遍歷,如下為遍歷過程:

  1. back每次加一
  2. back加一後,mid對從front開始到back之前的元素進行遍歷,並判斷mid和back所在位置的元素值是否相同
    • 如果相同,front指向mid+1位置元素,然後break跳出mid的遍歷
    • 如果不相同則mid++繼續遍歷直到相同或mid==back-1
  3. 如果front到back之前的元素均與back不相同,則將back-front+1和現存最大的字串長度相比較,取大的賦給max。

程式碼:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int max = 0;
        int len = s.size();
        if(len>0) max = 1;
        int front = 0;
        int back = front + 1;
        int mid = front;
        while(back<len){
            mid = front;
            bool flag =
false; do{//用mid對從front到back之前的值進行遍歷 if(s[mid]==s[back]){//如果相同,字串頭指向mid後一位 front = mid+1; flag = true; break; }else{//不相同繼續遍歷 mid++; } }while(mid<back); //如果front到back無重複元素,則將該子串長度與max比較,將最大的賦給max if(!flag) max = max<back-front+1?back-front+1:max; back++; } return max; } };