leetcode 3 Longest Substring Without Repeating Characters
2016-11-25 21:17
357 查看
用hashmap实现比较简单,其实质就是维护一个列表,根据列表元素个数来更新,如果列表中存在(设为m)就把之前那个m和它之前都删掉,从之前的m的后一个开始考虑
import java.util.HashMap;
import java.util.Map;
public class Solution {
public static int lengthOfLongestSubString(String s){
HashMap<Character,Integer>map=new HashMap<Character,Integer>();
int maxlength=0;
int start=0;
for (int i=0;i<s.length();i++){
if (!map.containsKey(s.charAt(i))){//如果这个数字没有在map中
map.put(s.charAt(i),i);
}
else{//否则出现过
if (map.size()>maxlength) {
maxlength=map.size();//更新
}
int end=map.get(s.charAt(i));//把从start~end中的数淘汰出map
for (int j=start;j<=end;j++){
map.remove(s.charAt(j));
}
start=end+1;//现在map中的起点
map.put(s.charAt(i), i);
}
}
if (map.size()>maxlength) {
maxlength=map.size();//更新
}
return maxlength;
}
public static void main(String args[]){
String s="aab";
System.out.println(Solution.lengthOfLongestSubString(s));
}
}
import java.util.HashMap;
import java.util.Map;
public class Solution {
public static int lengthOfLongestSubString(String s){
HashMap<Character,Integer>map=new HashMap<Character,Integer>();
int maxlength=0;
int start=0;
for (int i=0;i<s.length();i++){
if (!map.containsKey(s.charAt(i))){//如果这个数字没有在map中
map.put(s.charAt(i),i);
}
else{//否则出现过
if (map.size()>maxlength) {
maxlength=map.size();//更新
}
int end=map.get(s.charAt(i));//把从start~end中的数淘汰出map
for (int j=start;j<=end;j++){
map.remove(s.charAt(j));
}
start=end+1;//现在map中的起点
map.put(s.charAt(i), i);
}
}
if (map.size()>maxlength) {
maxlength=map.size();//更新
}
return maxlength;
}
public static void main(String args[]){
String s="aab";
System.out.println(Solution.lengthOfLongestSubString(s));
}
}
相关文章推荐
- Leetcode[3] Longest Substring Without Repeating Characters
- leetcode 3 golang实现 Longest Substring Without Repeating Characters
- LeetCode No.3 Longest Substring Without Repeating Characters
- LeetCode Longest Substring Without Repeating Characters
- 【LeetCode】003 Longest Substring Without Repeating Characters 最长的没有重复的子字符串
- leetcode[Longest Substring Without Repeating Characters]//待整理多种解法
- Leetcode Longest Substring Without Repeating Characters
- LeetCode: Longest Substring Without Repeating Characters
- LeetCode【3】Longest Substring Without Repeating Characters
- LeetCode第三题(Longest Substring Without Repeating Characters)
- [LeetCode]Longest Substring Without Repeating Characters
- Leetcode-- Longest Substring Without Repeating Characters
- 【LeetCode】Longest Substring Without Repeating Characters
- Leetcode(3):Longest Substring Without Repeating Characters
- [LeetCode]Longest Substring Without Repeating Characters
- 【LeetCode】3 Longest Substring Without Repeating Characters
- 3-Longest Substring Without Repeating Characters @LeetCode
- leetcode:Longest Substring Without Repeating Characters
- Leetcode: Longest Substring Without Repeating Characters
- LeetCode-003 Longest Substring Without Repeating Characters