Last active
May 16, 2017 11:15
-
-
Save BacLuc/5ed9c19225dbfb91fdc90baae6173aeb to your computer and use it in GitHub Desktop.
count two following x with overlapping
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Main{ | |
int countXX(String str) { | |
boolean lastOneIsX = false; | |
int countXX = 0; | |
for(int i=0;i<str.length(); i++){ | |
if(str.charAt(i)=="x".charAt(0)){ | |
if(lastOneIsX){ | |
countXX++; | |
} | |
lastOneIsX = true; | |
}else{ | |
lastOneIsX=false; | |
} | |
} | |
return countXX; | |
} | |
boolean doubleX(String str) { | |
/* | |
boolean doubleX(String str) { | |
int i = str.indexOf("x"); | |
if (i == -1) return false; // no "x" at all | |
// Is char at i+1 also an "x"? | |
if (i+1 >= str.length()) return false; // check i+1 in bounds? | |
return str.substring(i+1, i+2).equals("x"); | |
// Another approach -- .startsWith() simplifies the logic | |
// String x = str.substring(i); | |
// return x.startsWith("xx"); | |
} | |
*/ | |
int firstXIndex = str.indexOf("x"); | |
if(firstXIndex == str.length()-1)return false; | |
if(str.charAt(firstXIndex+1)=="x".charAt(0)) return true; | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
int countXX(String str) {
int count = 0;
for (int i = 0; i < str.length()-1; i++) {
if (str.substring(i, i+2).equals("xx")) count++;
}
return count;
}