首页 > 试题广场 >

牛牛喜欢c

[编程题]牛牛喜欢c
  • 热度指数:468 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
牛牛特别喜欢c这个字母,如果一个字符串中c这个字符的数量超过了整个字符串长度的一半,那么牛牛对这个字符串是十分满意的。
只不过,如果这个字符串不能使牛牛感到满意,那么他可以删去这个字符串中的某些字母,使得剩下的字符串让他感到满意。
那么,在牛牛可以执行删除某些字母情况下,让牛牛感到满意的字符串的长度最长是多少呢?
给定一个字符串s,返回让牛牛感到满意的字符串的最大的长度,题目保证字符串中含有c。
示例1

输入

"nowcoder"

输出

1

说明

"nowcoder"这个字符串中只有一个c,那么让牛牛感到满意的字符串的最大的长度也只能是1。 
示例2

输入

"cccdef"

输出

5

说明

"cccdef"这个字符串中有三个c,牛牛可以删除一个字符来使得这个字符串让他感到满意,那么让牛牛感到满意的字符串的最大的长度是5。 

备注:
  public int solve (String s) {
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == 'c') {
                count++;
            }
        }
        if(s.length() / 2 < count) {
            return s.length();
        } else {
            return 2 * count -1;
        }
    }
发表于 2021-06-13 23:01:05 回复(0)
public int solve(String s) {
    // write code here
    int count = 0;
    char[] chars = s.toCharArray();
    for (int i = 0; i < chars.length; i++) {
        if (chars[i] == 'c') {
            count++;
        }
    }
    if (count >= chars.length / 2) {
        return chars.length;
    }
    return count * 2 - 1;
}

发表于 2021-10-09 22:10:16 回复(0)
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 给定一个字符串s,返回让牛牛感到满意的字符串的最大的长度。
# @param s string字符串 代表题目中描述的s
# @return int整型
#
class Solution:
    def solve(self , s ):
        # write code here
        n = 0
        for i in range(len(s)):
            if s[i]=="c":
                n+=1
        return min(2*n-1,10**6)
发表于 2021-04-23 11:00:17 回复(0)
//如果一个字符串中c这个字符的数量超过了整个字符串长度的一半,
//那么牛牛对这个字符串是十分满意的。
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 给定一个字符串s,返回让牛牛感到满意的字符串的最大的长度。
     * @param s string字符串 代表题目中描述的s
     * @return int整型
     */
    int solve(string s) {
        // write code here
        if(s.size()==0) return 0;
        int cnum=0;
        for(char f: s) if(f=='c') cnum++;
        
        if(cnum> s.size()/2) return s.size();
        return cnum*2 -1;
        
        
    }
};

发表于 2021-04-06 17:56:46 回复(0)
 tmp = list(s)
        if tmp.count('c')>int(len(s)/2):
            return len(s)
        else:
            return tmp.count('c')*2-1
发表于 2021-03-26 17:49:07 回复(0)