Sunday, June 5, 2016

Java Challenge - doubleX - warm_up_2

Given a string, return true if the first instance of "x" in the string is immediately followed by another "x".

doubleX("axxbb") → true
doubleX("axaxax") → false
doubleX("xxxxx") → true

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
boolean doubleX(String str) {
 if(str.length() > 1)
  {
    int i = str.indexOf("x");
    if(i < str.length()-1)
      { 
       char l = str.charAt(i+1);
       if(l == 'x')return true;
      }
   }
 
   return false;
}



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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");
}

Java Challenge - countXX - warm_up_2

Count the number of "xx" in the given string. We'll say that overlapping is allowed, so "xxx" contains 2 "xx".

countXX("abcxx") → 1
countXX("xxx") → 2
countXX("xxxx") → 3

Solution :
1
2
3
4
5
6
7
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;
}