鄙人根据个人理解写的比较繁琐,大佬们海涵,如果有什么意见希望各位指点一二
题目(来自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;
}
};