LeetCode-3.Longest Substring Without Repeating Characters (Medium):
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.
我的做法:
考虑到最长子串不一定是从第一个字符开始的,所以用了一种比较笨的方法,比如adfafsadf,先查完整的adfafsadf从首字符开始的最长子串,是adf,然后去掉第一个字符,查dfafsadf从首字符开始的最长子串,是dfa。。。记录最长的子串就得到了结果。
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
count = 0
for i in range(0,len(s)):
tmp = s[i:]
count1 = 0
flag = ""
for j in tmp:
if flag.find(j)==-1:
flag = flag + j
count1 = count1 + 1
else:
break
if count1>count:
count = count1
return count
参考做法:
在网上看到一个java解法用到了set,我自己用上边的笨办法写了java代码提交运行时9ms,而用set解法是11ms,差不多,不过顺便学习一下java中各种集合(Collection)的用法吧:
Java 集合框架主要包括两种类型的容器,一种是集合(Collection),存储一个元素集合,另一种是图(Map),存储键/值对映射。Collection 接口又有 3 种子类型,List、Set 和 Queue,再下面是一些抽象类,最后是具体实现类,常用的有 ArrayList、LinkedList、HashSet、LinkedHashSet、HashMap、LinkedHashMap 等等。
程序中用到了HashSet保证添加进去的元素不重复,用变量i标记最长子串的开头,j标记最长子串的结尾,逐步后移,最终找到最大长度。
public class Solution {
public int lengthOfLongestSubstring(String s) {
Set<Character> set=new HashSet<>();
int m=s.length(),i=0,j=0,result=0;
while(i<m&&j<m)
{
if(set.contains(s.charAt(j)))
{
set.remove(s.charAt(i++));
//System.out.println("i="+i);
}
else
{
set.add(s.charAt(j++));
//System.out.println("j="+j);
result=Math.max(result,j-i);
}
}
return result;
}
}