Skip to content

Instantly share code, notes, and snippets.

@BacLuc
Last active May 16, 2017 11:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BacLuc/5ed9c19225dbfb91fdc90baae6173aeb to your computer and use it in GitHub Desktop.
Save BacLuc/5ed9c19225dbfb91fdc90baae6173aeb to your computer and use it in GitHub Desktop.
count two following x with overlapping
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;
}
}
@BacLuc
Copy link
Author

BacLuc commented May 16, 2017

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;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment