1. 程式人生 > >【Leetcode】【Longest Substring Without Repeating Characters】【無重復字符的最長子串】【C++】

【Leetcode】【Longest Substring Without Repeating Characters】【無重復字符的最長子串】【C++】

return ring sub 更新 sci ges 註意 code AC

  • 題目:給定一字符串,求其無重復字符的最長子串長度。
  • 思路:for循環一次,時間復雜度為O(N)。字符的ascii值為32~126。start表示當前無重復字符子串的初始位置,初始值為0;可定義一個位置數組pos[128]表示for循環索引到當前位置時相應的字符對應的位置。若當前字符s[i](其ascii值為cur_pos),若pos[cur_pos]>=start,說明在start之後已有該字符s[i],則以start開始的子串第一次遇到重復字符,打住。判斷當前長度是否大於max_len,若大於則更新max_len。然後更新start,以及pos[cur_pos]...。註意最後一個字符的處理。
  • 代碼:
    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            int len_s=s.size();
            const int M=128;
            int pos[M];
            for(int i=0;i<M;i++)
                pos[i]=-1;
    
            int start=0;
            int max_len=0;
    
            for(int i=0;i<len_s;i++)
            {
                
    int cur_pos=s[i]; if(pos[cur_pos]>=start) { if(max_len<(i-start)) { max_len=i-start; } start=pos[cur_pos]+1; } pos[cur_pos]=i; } if((len_s-start)>max_len) max_len
    =len_s-start; return max_len; } };

【Leetcode】【Longest Substring Without Repeating Characters】【無重復字符的最長子串】【C++】