Happy Ladybugs is a board game having the following properties:
1.The board is represented by a string,b, of length n. The ith character of the string,b[i], denotes the ith cell of the board.
1.1If is an underscore (i.e., _
), it means the ith cell of the board is empty.
1.2If b[i] is an uppercase English alphabetic letter (ascii[A-Z]), it means the ith cell contains a ladybug of color b[i].
1.3String b will not contain any other characters.
2. A ladybug is happy only when it's left or right adjacent cell (i.e., ) is occupied by another ladybug having the same color.
3. In a single move, you can move a ladybug from its current position to any empty cell.
Example:
Input: n=7, b="RBY_YBR"
Output: YES
Approach
Java
public class HappyLadybugs {public static void main(String[] args) {String b = "RBY_YBR";String result = happyLadybugs(b);System.out.println(result);}private static String happyLadybugs(String b) {int f[] = new int[26], cnt = 0;for (int i = 0; i < b.length(); i++) {if (b.charAt(i) >= 'A' && b.charAt(i) <= 'Z')f[b.charAt(i) - 'A']++;elsecnt++;}int flag = 0;for (int i = 0; i < 26; i++) {if (f[i] == 1) {flag = 1;break;}}if (flag == 1)return "NO";else {if (cnt > 0)return "YES";else {for (int i = 0; i < b.length() - 2; i++) {for (int j = i + 2; j < b.length(); j++) {if (b.charAt(j - 1) != b.charAt(i) && b.charAt(j) == b.charAt(i))return "NO";}}return "YES";}}}}
C++
#include <bits/stdc++.h>using namespace std;string happyLadybugs(string b){int f[26] = {0}, cnt = 0;for (int i = 0; i < b.size(); i++){if (b[i] >= 'A' && b[i] <= 'Z')f[b[i] - 'A']++;elsecnt++;}int flag = 0;for (int i = 0; i < 26; i++){if (f[i] == 1){flag = 1;break;}}if (flag == 1)return "NO";else{if (cnt > 0)return "YES";else{for (int i = 0; i < b.size() - 2; i++){for (int j = i + 2; j < b.size(); j++){if (b[j - 1] != b[i] && b[j] == b[i])return "NO";}}return "YES";}}}int main(){int n = 7;string b = "RBY_YBR";string result = happyLadybugs(b);cout << result << "\n";return 0;}
No comments:
Post a Comment