Problem:
Count the number of "xx" in the given string. We'll say that overlapping is allowed, so "xxx" contains 2 "xx".
countXX("abcxx") → 1
countXX("xxx") → 2
countXX("xxxx") → 3
Solution:
01 | int countXX(String str) { |
02 | int count = 0 ; |
03 | for ( int i = 0 ; i < str.length()- 1 ; i++) { |
04 | if (str.substring(i, i+ 2 ).equals( "xx" )) count++; |
05 | } |
06 | return count; |
07 | } |
08 |
09 | // Solution notes: the loop is shortened to end at str.length()-1 |
10 | // so we can pull out a length 2 substring without going out of bounds. |
11 | // Remember to use equals() to compare strings, not ==. |
public int countXX(String str)
ReplyDelete{
int count=0;
char[] arr=str.toCharArray();
for(int i=0;i<arr.length-1;i++)
{
if(arr[i]=='x'&&arr[i+1]=='x')
count++;
}
return count;
}
private final int countXX(String word) {
ReplyDeleteif(word.length() <= 2 && !word.equals("xx")){
return 0;
}
if(word.charAt(0) == 'x' && word.charAt(1) == 'x'){
return 1 + countXX(word.substring(1));
}
return countXX(word.substring(1));
}
int countXX(String str) {
ReplyDeleteint count = 0;
for(int i = 0; i < str.length()-1; i++){
if(str.charAt(i) == 'x' && str.charAt(i+1) == 'x'){
count++;
}
}
return count;
}