Problem:
Given a string, if the string begins with "red" or "blue" return that color string, otherwise return the empty string.
seeColor("redxx") → "red"
seeColor("xxred") → ""
seeColor("blueTimes") → "blue"
Solution:
public String seeColor(String str) { if (str.startsWith("red")) return "red"; if (str.startsWith("blue")) return "blue"; else return ""; }
public String seeColor(String str) {
ReplyDeleteif(str.length()>2 && "red".equals(str.substring(0,3)))
return "red";
else if(str.length()>3 && "blue".equals(str.substring(0,4)))
return "blue";
else return "";
}
public String seeColor(String str) {
ReplyDeleteif(str.length() >= 3 && str.substring(0,3).equals("red")) {
return "red";
} else if (str.length() >= 4 && str.substring(0,4).equals("blue")) {
return "blue";
}
return "";
}
public String seeColor(String str) {
ReplyDeleteint redIndex= str.indexOf("red");
int blueIndex = str.indexOf("blue");
if (redIndex == 0)
return "red";
else if (blueIndex == 0)
return "blue";
else
return "";
}
public String seeColor(String str) {
ReplyDeleteif(str.startsWith("red")){
return str.substring(0,3);
} if(str.startsWith("blue")){
return str.substring(0,4);
}
else return "";
}
public String seeColor(String str) {
ReplyDeleteif(str.indexOf("red") == 0) return "red";
if(str.indexOf("blue") == 0) return "blue";
return "";
}
return (str.length()>=2 && (str.substring(0,2).equals(str.substring(str.length()-2))));
ReplyDeleteSolution for wrong problem. Sorry
Deleteif (str.length()<=3 && !str.equals("red"))
ReplyDeletereturn "";
if (str.substring(0,3).equals("red"))
return "red";
if (str.substring(0,4).equals("blue"))
return "blue";
return "";
ReplyDeletereturn str.startsWith("blue") ? "blue" : str.startsWith("red") ? "red" : "";