[英]How to check if a String can be formed from the characters of another String in Java?
A string is good if it can be formed by characters from chars.如果字符串可以由字符中的字符组成,则它是好的。 I want to return the sum of lengths of all good strings in words.
我想用单词返回所有好字符串的长度总和。
Input: words = ["cat","bt","hat","tree"], chars = "atach"输入:words = ["cat","bt","hat","tree"], chars = "atach"
Output: 6 Output:6
Explanation: The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.解释:可以组成的字符串是“cat”和“hat”,所以答案是 3 + 3 = 6。
Below is the code that I have written.下面是我写的代码。
class Solution
{
public int countCharacters(String[] words, String chars)
{
int k = 0, count = 0;
Set<Character> set = new HashSet<>();
for(int i = 0; i < chars.length(); i++)
{
set.add(chars.charAt(i));
}
StringBuilder chrs = new StringBuilder();
for(Character ch : set)
{
chrs.append(ch);
}
for(int i = 0; i < words.length; i++)
{
char[] ch = words[i].toCharArray();
for(int j = 0; j < ch.length; j++)
{
if(chrs.contains("" + ch[j]))
{
k++;
}
}
if(k == words[i].length())
{
count+= k;
}
}
return count;
}
}
Output:
Line 24: error: cannot find symbol
if(chrs.contains("" + ch[j]))
Can someone help me?有人能帮我吗? What am I doing wrong in accessing the character?
我在访问角色时做错了什么?
contains
tells you if a string is contained in another string . contains
告诉您一个字符串是否包含在另一个字符串中。 But in your case ch[j]
is not a string but a char, so you can't use contains
.但是在您的情况下
ch[j]
不是字符串而是字符,因此您不能使用contains
。
Instead, use indexOf
, it returns -1
if the char is not present in the string.相反,使用
indexOf
,如果字符串中不存在字符,则返回-1
。
the most simple way is最简单的方法是
chars.contains("" + ch[i]);
Here, ch[j]
is not a string but a char, so you can't use contains as you've done.在这里,
ch[j]
不是一个字符串而是一个字符,所以你不能像以前那样使用 contains。 Instead, make the following change.相反,请进行以下更改。
chars.contains(String.valueOf(ch[j]));
The issues which I noticed is you are using contains()
to compare a String and a character.我注意到的问题是您使用
contains()
来比较字符串和字符。 But the contains()
method is a Java method to check if String contains another substring or not.但是
contains()
方法是一个 Java 方法来检查 String 是否包含另一个 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ 。
So you can solve this by converting the character to a string.因此,您可以通过将字符转换为字符串来解决此问题。
Ex 1:例 1:
if(chars.contains(Character.toString(ch[j]))){
k++;
} else {
}
Ex 2:例 2:
f(chars.contains(""+ch[j]))
{
k++;
} else {
}
Otherwise, You can compare if the string contains a char by using indexOf()
.否则,您可以使用
indexOf()
比较字符串是否包含字符。 If the string isn't containing the char it return -1.如果字符串不包含字符,则返回-1。 Please refer bellow example.
请参考下面的例子。
Ex:前任:
if(chars.indexOf(ch[j])!=-1){
k++;
} else {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.