For example, Given s =
“eceba”
, T is "ece" which its length is 3.
public class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
if (s == null || s.length() == 0) return 0;
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int start = 0;
map.put(s.charAt(0), 0);
int maxLen = 1;
for (int i = 1; i < s.length(); i++) {
char c = s.charAt(i);
if (map.containsKey(c) || map.size() < 2) {
map.put(c, i);
maxLen = Math.max(maxLen, i - start + 1);
} else {
Iterator<Character> iterator = map.keySet().iterator();
char c1 = iterator.next();
char c2 = iterator.next();
int p1 = map.get(c1);
int p2 = map.get(c2);
if (p1 < p2) {
start = p1 + 1;
map.remove(c1);
} else {
start = p2 + 1;
map.remove(c2);
}
map.put(c, i);
}
}
return maxLen;
}
}
==========
public class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int c1 = -1;
int c2 = -1;
int res = 0;
int start = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c1 == -1 || s.charAt(c1) == c) {
c1 = i;
res = Math.max(i - start + 1, res);
} else if (c2 == -1 || s.charAt(c2) == c) {
c2 = i;
res = Math.max(i - start + 1, res);
} else {
if (c1 < c2) {
start = c1 + 1;
c1 = i;
} else {
start = c2 + 1;
c2 = i;
}
}
}
return res;
}
}
==========
public class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
if (s == null || s.length() == 0) return 0;
int start = 0;
int c1 = -1;
int c2 = -1;
int maxLen = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c1 == -1 || s.charAt(c1) == s.charAt(i)) {
c1 = i;
maxLen = Math.max(maxLen, i - start + 1);
} else if ((c2 == -1 && s.charAt(i) != s.charAt(c1)) || s.charAt(c2) == s.charAt(i)) {
c2 = i;
maxLen = Math.max(maxLen, i - start + 1);
} else {
if (c1 < c2) {
start = c1 + 1;
c1 = i;
} else {
start = c2 + 1;
c2 = i;
}
}
}
return maxLen;
}
}
==========
public class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int start = 0;
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int end = 0;
int res = 1;
map.put(s.charAt(start), 0);
while (end < s.length()) {
if (map.size() > 2) {
if (map.get(s.charAt(start)) == start)
map.remove(s.charAt(start));
start++;
}
if (map.size() <= 2) {
res = Math.max(end - start + 1, res);
end++;
if (end != s.length())
map.put(s.charAt(end), end);
}
}
return res;
}
}
没有评论:
发表评论