C++零基础算法100题 - 字母在字符串中的百分比

97 阅读1分钟

题目链接: 2278. 字母在字符串中的百分比 - 力扣(LeetCode)

题目描述

image.png

步骤讲解

  1. 我们得到一个字符串和一个要查找的letter
  2. 我们获取到这个字符串中有多少个letter
  3. 求letter在字符串中占比的方法为[cnt*100/s.size()]

代码实现

class Solution {
public:
    int percentageLetter(string s, char letter) {
        int cnt=0;
        for(int i=0;i<s.size();i++){
            if(s[i]==letter){
                cnt++;
            }
        }
        return cnt*100/s.size();
    }
};