leetcode 3. Longest Substring Without Repeating Characters
2016-05-31 09:31
381 查看
题目
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given
which the length is 3.
Given
with the length of 1.
Given
with the length of 3. Note that the answer must be a substring,
a subsequence and not a substring.
思路:利用一个exist数组保存字符是否出现(假设char set是ascii),从前向后遍历数组,如果遇到已存在的字符,应该回退到这个字符上次出现的下一个位置从新开始统计,同时注意exist数组的同步更新。
代码public class Solution {
public int lengthOfLongestSubstring(String s) {
if(s.equals("")){
return 0;
}
int res = 1;
int start = 0;
boolean exist[] = new boolean[128];
for(int i = 0;i < 128; i++){
exist[i] = false;
}
for(int i = 0;i < s.length(); i++){
char c = s.charAt(i);
if(exist[c]){
for(int k = start;k < i; k++){
if(s.charAt(k)==c){
start = k+1;
break;
}
exist[s.charAt(k)] = false;
}
}else{
exist[c] = true;
}
if((i-start+1) > res){
res = i - start + 1;
}
}
return res;
}
}
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given
"abcabcbb", the answer is
"abc",
which the length is 3.
Given
"bbbbb", the answer is
"b",
with the length of 1.
Given
"pwwkew", the answer is
"wke",
with the length of 3. Note that the answer must be a substring,
"pwke"is
a subsequence and not a substring.
思路:利用一个exist数组保存字符是否出现(假设char set是ascii),从前向后遍历数组,如果遇到已存在的字符,应该回退到这个字符上次出现的下一个位置从新开始统计,同时注意exist数组的同步更新。
代码public class Solution {
public int lengthOfLongestSubstring(String s) {
if(s.equals("")){
return 0;
}
int res = 1;
int start = 0;
boolean exist[] = new boolean[128];
for(int i = 0;i < 128; i++){
exist[i] = false;
}
for(int i = 0;i < s.length(); i++){
char c = s.charAt(i);
if(exist[c]){
for(int k = start;k < i; k++){
if(s.charAt(k)==c){
start = k+1;
break;
}
exist[s.charAt(k)] = false;
}
}else{
exist[c] = true;
}
if((i-start+1) > res){
res = i - start + 1;
}
}
return res;
}
}
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解