leetcode:Longest Substring Without Repeating Characters
2014-06-16 18:45
344 查看
求出串S最长的不重复子串
定义数组ans[] , ans[i]表示以第i个字符结尾的最长不重复子串的长度为ans[i],
那么可知:
ans[i] = ans[i - 1] + 1,如果第i个字符在S(i - 1 - ans[i - 1])......S(i -1)的范围内没有出现过
否则 ans[i] = i - 最后一次出现的位置;
public class Solution {
public int lengthOfLongestSubstring(String s) {
if (s.length() == 0) {
return 0;
}
HashMap<Character, Integer> map = new HashMap<>();
int[] ans = new int[s.length()];
ans[0] = 1;
map.put(s.charAt(0), 0);
int max = 1;
for (int i = 1, len = s.length(); i < len; ++i) {
Integer site = map.get(s.charAt(i));
if (site == null || site < i - ans[i - 1]) {
ans[i] = ans[i - 1] + 1;
} else {
ans[i] = i - site;
}
map.put(s.charAt(i), i);
if (ans[i] > max) {
max = ans[i];
}
}
// for (int k : ans) {
// System.out.print(k + " ");
// }
return max;
}
}
定义数组ans[] , ans[i]表示以第i个字符结尾的最长不重复子串的长度为ans[i],
那么可知:
ans[i] = ans[i - 1] + 1,如果第i个字符在S(i - 1 - ans[i - 1])......S(i -1)的范围内没有出现过
否则 ans[i] = i - 最后一次出现的位置;
public class Solution {
public int lengthOfLongestSubstring(String s) {
if (s.length() == 0) {
return 0;
}
HashMap<Character, Integer> map = new HashMap<>();
int[] ans = new int[s.length()];
ans[0] = 1;
map.put(s.charAt(0), 0);
int max = 1;
for (int i = 1, len = s.length(); i < len; ++i) {
Integer site = map.get(s.charAt(i));
if (site == null || site < i - ans[i - 1]) {
ans[i] = ans[i - 1] + 1;
} else {
ans[i] = i - site;
}
map.put(s.charAt(i), i);
if (ans[i] > max) {
max = ans[i];
}
}
// for (int k : ans) {
// System.out.print(k + " ");
// }
return max;
}
}
相关文章推荐
- [leetcode]Longest Substring Without Repeating Characters【最长不重复字符子串】
- LeetCode No.3 Longest Substring Without Repeating Characters
- LeetCode - Longest Substring Without Repeating Characters hash
- [LeetCode] Longest Substring Without Repeating Characters Python
- LeetCode 3 Longest Substring Without Repeating Characters
- LeetCode | Longest Substring Without Repeating Characters
- LeetCode(3)Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters -- LeetCode
- [LeetCode][3]Longest Substring Without Repeating Characters解析 -Java实现
- LeetCode - Longest Substring Without Repeating Characters
- LeetCode Longest Substring Without Repeating Characters
- Leetcode题解:4. Longest Substring Without Repeating Characters
- Leetcode: Longest Substring Without Repeating Characters
- leetcode:Longest Substring Without Repeating Characters
- [LeetCode][Java] Longest Substring Without Repeating Characters
- LeetCode Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- [leetcode] Longest Substring Without Repeating Characters
- Leetcode_003_Longest_Substring_Without_Repeating_Characters
- 【编程】leetcode_longest substring without repeating characters