Java > Warmup-2 > doubleX (CodingBat Solution)

Problem:

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


Solution:

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

7 comments:

  1. boolean doubleX(String str) {

    for(int i=0;i<str.length()-1;i++){
    if(str.charAt(i)=='x'){
    if (str.charAt(i+1)=='x') {
    return true;
    } else {
    return false;
    }
    }
    }
    return false;
    }

    ReplyDelete
  2. private final boolean doubleX(String word) {
    return (word.indexOf("x") >= 0) && word.substring(word.indexOf("x")).startsWith("xx");
    }

    ReplyDelete
  3. private final boolean doubleX(String word) {
    if(word.indexOf("x") < 0) {
    return false;
    }
    return word.substring(word.indexOf("x")).startsWith("xx");
    }

    ReplyDelete
  4. boolean doubleX(String str) {
    return str.startsWith("xx")||str.startsWith("xx",1) ;
    }

    ReplyDelete
  5. Another way

    boolean doubleX(String str) {
    return !str.contains("x") ? false :
    str.substring(str.indexOf("x")).startsWith("xx");
    }

    ReplyDelete
  6. boolean doubleX(String str) {
    boolean ans=false;
    int index =str.indexOf("x"), len =str.length();

    if (index !=-1 && index<len-1 ){
    String s = str.substring(index);
    if (s.startsWith("xx")) {
    ans =true;
    }
    }
    return ans;
    }

    ReplyDelete