leetcode003:Longest Substring Without Repeating Characters

問題描述

Longest Substring Without Repeating Characters
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.

思路描述

尋找字符串中最長的非重複字符的子串。思路:abcdefc,出現重複字符則截斷從重複字符後一個字符開始的子串“defc”繼續統計非重複字符子串,最終達到最長非重複字符子串!

代碼

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        string s1 ;
        int ans=0;
        int count=0;
        int idx;
        for (int i = 0; i < s.length(); i++)
        {
            if ((idx = s1.find(s[i], 0)) == string::npos)
            {
                s1 += s[i];
                count++;
            }
            else
            {
                if (count>ans) ans = count;
                s1 = s1.substr(idx + 1) + s[i];
                count = s1.length();
            }
        }
        return count > ans ? count : ans;
    }
};
發佈了60 篇原創文章 · 獲贊 8 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章