# Any one has a 5-10% lead solution?

• Is there better method for ordinary counting?

• 6ms 98.61% java solution

``````public int lengthOfLongestSubstringTwoDistinct(String s) {
int n = s.length();
if (n < 3) return n;

char [] values = new char [2];
int [] idxLast = new int [2];
int start;

int i = 0;
while (i < n && s.charAt(i) == s.charAt(0))  i++;
if (i == n) return n;

values[0] = s.charAt(0); values[1] = s.charAt(i);
idxLast[0] = i - 1; idxLast[1] = i;
start = 0;

int lenMax = i + 1;

for (; i < n; i++) {
char c = s.charAt(i);
if (c == values[0]) {
idxLast[0] = i;
} else if (c == values[1]) {
idxLast[1] = i;
} else {
if (i - start > lenMax) lenMax = i - start;
if (idxLast[0] > idxLast[1]) { //replace 1
start = idxLast[1] + 1;
idxLast[1] = i;
values[1] = c;
} else { // replace 0
start = idxLast[0] + 1;
idxLast[0] = i;
values[0] = c;
}
}
}
if (n - start > lenMax) lenMax = n - start;
return lenMax;
}``````

• Beats 99.64% java solns -

``````public class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
char oneBefore='.', twoBefore='-';
int currentCount = 0, max = 0;

char[] cs = s.toCharArray();
for(int i=0; i< cs.length; i++){
if(cs[i] == oneBefore || cs[i] == twoBefore) {
currentCount++;
}
else{
currentCount = updateCount(cs,i);
oneBefore = cs[i];
if(i>=1){
twoBefore = cs[i-1];
}
}
if (currentCount > max){
max=currentCount;
}
}
return max;
}
public int updateCount(char[] s, int i){
int count = 1;
if (i<=0){
return count;
}
int j = i-1;
while(j>=0){
if(s[i-1] == s[j]){
count++;
}
else{
break;
}
--j;
}
return count;
}
}``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.