如何检查一个字符串是否可以由Java中另一个字符串的字符组成?

问题描述 投票:0回答:3

如果字符串可以由字符中的字符组成,则字符串是好的。我想返回所有好的字符串的长度之和。

输入:words = [“ cat”,“ bt”,“ hat”,“ tree”],chars =“ atach”

输出:6

说明:可以形成的字符串是“ cat”和“ hat”,因此答案是3 + 3 = 6。

下面是我编写的代码。

class Solution
{
    public int countCharacters(String[] words, String chars) 
    {
        int k = 0,count=0;

        for(int i = 0; i < words.length; i++)
        {
            char[] ch = words[i].toCharArray();

            for(int j = 0; j < ch.length; j++)
            {
                if(chars.contains(ch[j]))
                {
                    k++;

                }
            }

            if(k == words[i].length())
            {
                count+= Math.max(count,k);
            }
        }

        return count;
    }
}

Output:
Line 13: error: incompatible types: char cannot be converted to CharSequence
                if(chars.contains(ch[j]))

有人可以帮我吗?访问角色时我做错了什么?

java string
3个回答
0
投票

contains告诉您另一个string中是否包含一个string。但是,在您的情况下,contains不是字符串而是字符,因此您不能使用ch[j]

相反,使用contains,如果字符串中不存在字符,则返回indexOf


0
投票

最简单的方法是

indexOf

0
投票

这里,-1不是字符串,而是一个字符,因此您不能像完成那样使用contains。相反,进行以下更改。

chars.contains("" + ch[i]);
© www.soinside.com 2019 - 2024. All rights reserved.