Online challenge on Hacker Rank.
Alice has a binary string,
B
, of lengthn
. She thinks a binary string is beautiful if and only if it doesn't contain the substring010
.In one step, Alice can change a
0
to1
a (or vice-versa). Count and print the minimum number of steps needed to make Alice see the string as beautiful.Input Format
The first line contains an integer,
n
(the length of binary stringB
). The second line contains a single binary string,B
, of lengthn
.Output Format
Print the minimum number of steps needed to make the string beautiful.
public class Solution {
private static int countChange(String text, String pattern) {
int textLen = text.length();
int patternLen = pattern.length();
char[] chars = text.toCharArray();
int count = 0;
for (int i = 0; i <= textLen - patternLen; i++) {
int j = 0;
while (j < patternLen && chars[i+j] == pattern.charAt(j)) {
j++;
}
if (j == patternLen) {
count++;
chars[i+2] = '1';
}
}
return count;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String B = in.next();
System.out.println(countChange(B, "010"));
}
}
String.indexOf(pattern, n)
to find the next occurrence of the pattern. Changen
to step along the binary string as each copy of the pattern is found. \$\endgroup\$