Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

2278. Percentage of Letter in String

String

Explanation:

To solve this problem, we need to iterate through the given string s and count the number of occurrences of the character letter. Then we calculate the percentage of occurrences of letter in s and round it down to the nearest whole percentage.

  1. Initialize a variable count to store the number of occurrences of letter.
  2. Iterate through each character in the string s:
    • If the character is equal to letter, increment the count.
  3. Calculate the percentage of occurrences of letter in s by dividing count by the length of s and multiplying by 100.
  4. Return the rounded down value of the percentage.

:

class Solution {
    public int percentageOfLetterInString(String s, char letter) {
        int count = 0;
        for (char c : s.toCharArray()) {
            if (c == letter) {
                count++;
            }
        }
        return count * 100 / s.length();
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.