#3 无重复字符的最长子串 Longest Substring Without Repeating Characters
给定一个字符串,找出不含有重复字符的 最长子串 的长度。
Given a string, find the length of the longest substring without repeating characters.
示例:
给定 "abcabcbb"
,没有重复字符的最长子串是 "abc"
,那么长度就是3。
给定 "bbbbb"
,最长的子串就是 "b"
,长度是1。
给定 "pwwkew"
,最长子串是 "wke"
,长度是3。请注意答案必须是一个子串,"pwke"
是 子序列 而不是子串。
初级思路:
声明当前子串长度、最长子串长度和是否循环完毕标志位(判断循环是因为元素正常循环完毕还是中途有不符合条件的内容出现)。设定双循环对每个字符从当前位置向后查找有没有相同的字符,遇到则将标志位置否;外循环中如标志位为真则增加当前子串长度,如超过最长长度则取代之。
*缺陷:时间复杂度O(n^2)
代码(Java):
class Solution {
public int lengthOfLongestSubstring(String s) {
int i=1,j=0;
int head=0;
int length=1,max_length=1;
boolean is_full=true;
if(s.length()==0){
return 0;
}
while(i<s.length()){
for(j=head;j<i;j++){
if(s.charAt(i)==s.charAt(j)){
length=i-j;
head=j+1;
is_full=false;
}
}
i++;
if(is_full==true){
length++;
}
else{
is_full=true;
}
if(length>max_length){
max_length=length;
}
}
return max_length;
}
}
进阶思路:
将字符串内容及其标号单循环依次存入散列表,如遇到有与之前相同的字符则提取之前的字符标号,计算长度是否超过当前最大值,是则取代之。
代码(Java):
public int lengthOfLongestSubstring(String s) {
if (s.length()==0) return 0;
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int max=0;
for (int i=0, j=0; i<s.length(); ++i){
if (map.containsKey(s.charAt(i))){
j = Math.max(j,map.get(s.charAt(i))+1);
}
map.put(s.charAt(i),i);
max = Math.max(max,i-j+1);
}
return max;
}