您的位置:首页 > 其它

Leetcode 3. Longest Substring Without Repeating Characters

2017-01-15 03:46 399 查看
O(n)

public class Solution {
public int lengthOfLongestSubstring(String s) {
HashSet<Character> hs = new HashSet<Character>();
int max = 0, fast = 0, slow = 0;
while (fast < s.length()) {
if (!hs.add(s.charAt(fast))) {
hs.remove(s.charAt(slow));
slow++;
}
else {
// maintain the maximum length
max = Math.max(max, fast-slow+1);
fast++;
}
}
return max;
}
}
O(n^2)

// using a hashset to save the sunstring starting from 0, 1, ..., n
// keep recording the length for each substring
// if max < current length, set max = current length
public class Solution {
public int lengthOfLongestSubstring(String s) {
HashSet<Character> hs = new HashSet<Character>();
int max = 0;

// check the length for substring starts from i
for (int i=0; i<s.length(); i++) {
// tmp to save the current substring's length
int tmp = 0, j = i;
while (j < s.length()) {
// found a duplicate character
if (!hs.add(s.charAt(j)))
break;
tmp++;
j++;
}
// clear the hashset after each iteration
hs.clear();
// save the maximum length
max = Math.max(tmp, max);
}

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