Problem:
Given a string, return the count of the number of times that a substring length 2 appears in the string and also as the last 2 chars of the string, so "hixxxhi" yields 1 (we won't count the end substring).
last2("hixxhi") → 1
last2("xaxxaxaxx") → 1
last2("axxxaaxx") → 2
Solution:
public int last2(String str) { if (str.length() < 2) return 0; String end = str.substring(str.length()-2); int count = 0; for (int i=0; i<str.length()-2; i++) { String sub = str.substring(i, i+2); if (sub.equals(end)) { count++; } } return count; }
public int last2(String str) {
ReplyDeleteint len = str.length();
int count = 0;
if(len <= 2){
return 0;
}
for(int i = 0; i < len-2; i++){
String last = str.substring(len-2);
if(str.substring(i, i+2).equals(last)){
count++;
}
}
return count;
}
public int last2(String str) {
ReplyDeleteint count=0;
int len=str.length();
for (int i = 0; i <len-2 ; i++) {
if(str.substring(len-2).compareTo(str.substring(i,i+2))==0){
count++;
}
}
return count;
}