您的位置:首页 > 其它

LeetCode OJ 3. Longest Substring Without Repeating Characters

2016-03-24 15:26 281 查看

题目大意

  给定一个字符串,求出该字符串中最长不重复子串的长度。

用Map接口(适用于UTF-8字符集):

public class Main {

public static void main(String[] args) {
// TODO Auto-generated method stub
Solution ss = new Solution();
System.out.println(ss.lengthOfLongestSubstring("asadfasdfasdfa"));

}

}

class Solution {
public int lengthOfLongestSubstring(String s) {
if(s == null)
return 0;

int ans = 0;
//用来保存不重复子串的左边界
int left = 0;

//Map记录了出现过的字符和对应的位置
Map<Character, Integer> map = new HashMap<>();

for(int i = 0;i < s.length();i++){
char ch =  s.charAt(i);
//判读当前字符是否在之前遍历的过程中出现过
//若出现过,则更新左边界
if(map.containsKey(ch) && map.get(ch) >= left){
left = map.get(ch)+1;
}
//若没有出现过,则更新结果
else {
ans = Math.max(ans, i-left+1);
}
//跟新出现过的字符
map.put(ch, i);
}

return ans;
}
}

用数组记录字符出现的位置(此种方法相比上面的方法在应用范围上有所限制,只能应用ASCII字符集):

该方法可以通过测试说明测试数据是ASCII字符集。

public class Solution {
public int lengthOfLongestSubstring(String s) {
if(s == null)
return 0;

int ans = 0;
//用来保存不重复子串的左边界
int left = 0;

//map记录了出现过的字符和对应的位置
int[] map = new int[260];
Arrays.fill(map, -1);

for(int i = 0;i < s.length();i++){
char ch =  s.charAt(i);
//判读当前字符是否在之前遍历的过程中出现过
//若出现过,则更新左边界
if(map[ch] != -1 && map[ch] >= left){
left = map[ch]+1;
}
//若没有出现过,则更新结果
else {
ans = Math.max(ans, i-left+1);
}
//跟新出现过的字符
map[ch] = i;
}

return ans;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: