[Programmers / JAVA] Level 1 Count of p and y in a String (12916)
[Programmers / JAVA] Level 1 Count of p and y in a String (12916)
| Rank | Language Used |
|---|---|
| Level 1 | 🖼️ JAVA |
🔗 Count of p and y in a String
You are given a string s consisting of a mix of uppercase and lowercase letters. Complete the solution function that returns True if the count of 'p' and the count of 'y' in s are equal, and False otherwise. If neither 'p' nor 'y' appears at all, it should always return True. Note that when comparing counts, uppercase and lowercase are not distinguished.
For example, if s is "pPoooyY", it returns true, and if it is "Pyy", it returns false.
- Length of string s: a natural number of 50 or less
- String s consists only of alphabet letters.
| s | answer |
|---|---|
| "pPoooyY" | true |
| "Pyy" | false |
Input/Output Example #1
There are 2 occurrences of 'p' and 2 of 'y', so they're equal, and it returns true.
Input/Output Example #2
There is 1 occurrence of 'p' and 2 of 'y', so they differ, and it returns false.
A simple problem where you just need to compare the counts of p and y in the string, returning true if they're equal and false otherwise.
Since p and y comparisons are not case-sensitive, apply the toLowerCase() method for convenience to make everything lowercase.
Then, traverse each character of string s, tally up the counts of p and y, and compare them.
Here, we take the approach of splitting s into individual characters to form an array, then using a stream to compute and compare the counts of p and y.
JAVA
import java.util.Arrays; /** * Count of p and y in a String class * * @author RWB * @since 2021.12.13 Mon 15:01:11 */ class Solution { /** * Method that returns the answer * * @param s: [String] string * * @return [String[]] the answer */ public boolean solution(String s) { int p = (int) Arrays.stream(s.toLowerCase().split("")).filter(item -> item.equals("p")).count(); int y = (int) Arrays.stream(s.toLowerCase().split("")).filter(item -> item.equals("y")).count(); return p == y; } }
Besides applying toLowerCase(), you could also use equalsIgnoreCase() to compare the characters regardless of case.
