1. 程式人生 > >LeetCode Longest Substring Without Repeating Characters Python C++ 實現

LeetCode Longest Substring Without Repeating Characters Python C++ 實現

鄙人根據個人理解寫的比較繁瑣,大佬們海涵,如果有什麼意見希望各位指點一二

題目(來自leetcode網站):

利用python3 或者 C++來實現

題目含義基本為:從給定的一整個字串中找出一個不包含重複字元的最長且連續的字串,的“長度”。

Given a string, find the length of the longest substring without repeating characters.

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc"
, with the length of 3.

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: 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.

解答:

#Python
from collections import defaultdict

class Solution:
    def lengthOfLongestSubstring(self,s):
        """
        :type s: str
        :rtype: int
        """
        z=defaultdict(int)
        max=0
        count=0
        i=0
        start=0
        if len(s)>0:
            while(i < len(s)):
                if z[s[i]] ==0:
                    count+=1
                    z[s[i]]+=1
                    i+=1
                else:
                    max = count if count>max else max
                    start+=1
                    z=defaultdict(int)
                    i=start
                    count=0
            max = count if count >max else max
            return max
        else:
            return 0

#C++
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int s_length=s.length();
        int i=0;
        int start=0;
        int count=0;
        int max=0;
        string b="";
        string::size_type idx;
        while(i<s_length){
            idx =b.find(s[i]);
            if ( idx == string::npos ){
                b+=s[i];
                i++;
            }
            else{
                max = max > b.length()? max :b.length();
                start++;
                i=start;
                b="";
            }
            
            
        }
        max = max > b.length()? max:b.length();
        return max;
    }
};