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"); }
boolean doubleX(String str) {
ReplyDeletefor(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;
}
private final boolean doubleX(String word) {
ReplyDeletereturn (word.indexOf("x") >= 0) && word.substring(word.indexOf("x")).startsWith("xx");
}
private final boolean doubleX(String word) {
ReplyDeleteif(word.indexOf("x") < 0) {
return false;
}
return word.substring(word.indexOf("x")).startsWith("xx");
}
boolean doubleX(String str) {
ReplyDeletereturn str.startsWith("xx")||str.startsWith("xx",1) ;
}
Another way
ReplyDeleteboolean doubleX(String str) {
return !str.contains("x") ? false :
str.substring(str.indexOf("x")).startsWith("xx");
}
boolean doubleX(String str) {
ReplyDeleteboolean 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;
}
second way
Delete