Title: Longest Substring without Repeating Characters
Description:
Given a string, find the length of the longest substring without repeating characters.
Analysis:
1. list all the substrings exhaustily.
2. insert i, j as start and end poster.then justify if the substring has no repeating characters.
time spends: o(n^2). space spend:o(n)
3. improved from (2), if the j th has been appeared in the i-j substring, j will be added in and i should auto-increased to non-repeating.
that is to say: in given input = "abcb", when i =0, j =3, abcb has repeating'b', we will set i++ until to 2, at this time, i = 2, j =3."cb"
4. improved from (3). we can use hashmap to store the index of the redundancy character rather than auto-increase.
for 3).
answer will be:
package com.connie;
import java.util.HashSet;
import java.util.Set;
public class Leetcode3 {
public static void main(String[] args) {
// write your code here
System.out.print(longSubString("pwwkew")+","+longSubString("abcabcbb"));
}
private static int longSubString(String str) {
int longest = 1, i = 0, j = 1;
Set subStr = new HashSet();
subStr.add(str.charAt(i));
while(i<str.length() && j<str.length()){
if(!subStr.contains(str.charAt(j))){
subStr.add(str.charAt(j++));
longest = Math.max(longest, j-i);
} else {
// if(i+1 == j) {
// j++;
// i++;
// } else {
subStr.remove(str.charAt(i++));
// }
}
}
return longest;
}
}
for 4)..
package com.connie;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class Leetcode3 {
public static void main(String[] args) {
// write your code here
System.out.print(longSubString("pwwkew")+","+longSubString("abcabcbb"));
}
private static int longSubString(String str) {
int longest = 1, i = 0, j = 1;
Map subStr = new HashMap();
subStr.put(str.charAt(i), i);
while(i<str.length() && j<str.length()) {
if(subStr.containsKey(str.charAt(j))) {
i = (Integer) subStr.get(str.charAt(j))+1;
}
subStr.put(str.charAt(j), j);
j++;
longest = Math.max(longest, j-i);
}
return longest;
}
}
浙公网安备 33010602011771号