Reputation: 25
Count the number of times aaa
appears in a string, 1. without repetition and 2. when repetition is allowed. I tried the following code which works well for 1st case but does'nt work well for the second case.
public static void main(String[] args) {
String str="cbaadaaabefaaaag";
int count=0,count1=0;
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)=='a' && str.charAt(i+1)=='a' && str.charAt(i+2)=='a')
{
count++;
}
}
System.out.println(count);
for(int i=0;i<str.length();i++)
{
if(i==0)
{
if(str.charAt(i)=='a' && str.charAt(i+1)=='a' && str.charAt(i+2)=='a')
{
count1++;
}
}
else
{
if(str.charAt(i-1)=='a' && str.charAt(i)=='a' && str.charAt(i+1)=='a')
{
count1++;
}
}
}
System.out.println(count1);
}
The input I tried is cbaadaaabefaaaag
which should give 3 for 1st case and 2 for 2nd case, also when the input is aaaa
it should be 1 for 1st case and 2 for overlaping case.
Upvotes: 0
Views: 383
Reputation: 17
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
String str = scn.nextLine();
int count = 0, count1 = 0;
for (int i = 0; i < str.length() - 2; i++) {
if (str.charAt(i) == 'a' && str.charAt(i + 1) == 'a' && str.charAt(i + 2) == 'a') {
count++;
}
}
System.out.println(count);
for (int i = 0; i <= str.length() -1; i++) {
if (str.charAt(i) == 'a' && str.charAt(i + 1) == 'a' && str.charAt(i + 2) == 'a') {
i += 2;
count1++;
}
}
System.out.println(count1);
}
Upvotes: 0
Reputation: 22099
This code should help you:
public static void main(String args[]) throws Exception {
String str = "cbaadaaabefaaaaaaag";
System.out.println(count(str, true));
System.out.println(count(str, false));
}
public static int count(String str, boolean overlap) {
int count = 0;
for (int i = 0; i < str.length() - 2; i++) {
if (str.charAt(i) == 'a' && str.charAt(i + 1) == 'a'
&& str.charAt(i + 2) == 'a') {
if (!overlap) {
i += 2;
}
count++;
}
}
return count;
}
The condition i < str.length() - 2
ensures that you do not get a StringIndexOutOfBoundsException
, because if there are only two characters left in the string, there cannot be anther substring aaa
.
The overlap condition adds two to the current index, where a substring aaa
was found, so your index points to the next character after the last found sequence aaa
, which prevents overlapping.
Upvotes: 3