(Coderbyte) AB Check - Solução
Have the function ABCheck(str) take the str parameter being passed and return the string true if the characters a and b are separated by exactly 3 places anywhere in the string at least once (ie. "lane borrowed" would result in true because there is exactly three characters between a and b). Otherwise return the string false.
Solução:
import java.util.*;
import java.io.*;
class Function {
String ABCheck(String str) {
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'a' || str.charAt(i) == 'b') {
int count = 0;
for(int j = i+1; j < str.length(); j++) {
if (((str.charAt(j) == 'b' && str.charAt(i) == 'a') || (str.charAt(j) == 'a' && str.charAt(i) == 'b')) && count == 3) {
return "true";
}
count++;
}
}
}
return "false";
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
Function c = new Function();
System.out.print(c.ABCheck(s.nextLine()));
}
}
Solução:
import java.util.*;
import java.io.*;
class Function {
String ABCheck(String str) {
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'a' || str.charAt(i) == 'b') {
int count = 0;
for(int j = i+1; j < str.length(); j++) {
if (((str.charAt(j) == 'b' && str.charAt(i) == 'a') || (str.charAt(j) == 'a' && str.charAt(i) == 'b')) && count == 3) {
return "true";
}
count++;
}
}
}
return "false";
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
Function c = new Function();
System.out.print(c.ABCheck(s.nextLine()));
}
}
Comments
Post a Comment