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"); } |
No comments:
Post a Comment