[英]How to check that one String can be spelled using characters from another String?
Example: String a = "ACAHBBA" and String b = "ABAB" should return true, since both strings can spell ABAB. 示例:字符串a =“ ACAHBBA”和字符串b =“ ABAB”应该返回true,因为两个字符串都可以拼写ABAB。
I have tried with contains(), but that only works for equal sequences. 我已经尝试过contains(),但这仅适用于相等的序列。
// The code should look like this.
public class task10 {
public static boolean contains(String a, String b) {
// check if b can be spelled using characters from a.
// if it can. return true.
// else
return false;
}
}
Posible solution? 可能的解决方案?
public static boolean contains(String a, String b) {
for (int i = 0; i < b.length(); i++) {
if (a.indexOf(b.charAt(i)) == -1) {
return false;
}
}
return true;
}
Simply iterate thru one string and get the index of the character. 只需遍历一个字符串并获得字符的索引。 If >= 0, replace character with non-alphabetic character and repeat.
如果> = 0,则将字符替换为非字母字符并重复。 This algorithm presumes the need to match the correct number of characters.
该算法假定需要匹配正确的字符数。 For example,
hello
would return false if the character set was helo
. 例如,如果字符集为
helo
, hello
将返回false。
public static boolean spelledFrom(String word, String chars) {
StringBuilder sb = new StringBuilder(chars);
for (String c : word.split("")) {
int i;
if ((i = sb.indexOf(c)) < 0) {
return false;
}
sb.setCharAt(i, '#');
}
return true;
}
You can try this: 您可以尝试以下方法:
public static boolean canSpell(String a, String b)
{
String shorter = (a.length() <= b.length()) ? a : b;
String longer = (shorter.equals(a)) ? b : a;
for(int i = 0; i < shorter.length(); i++)
{
if(!longer.contains("" + shorter.charAt(i)))
return false;
}
return true;
}
Once you've identified the shorter string, you just need to verify that each of its chars are contained in the longer string. 一旦确定了较短的字符串,您只需要验证其每个字符都包含在较长的字符串中即可。 This solution doesn't verify if a char "has already been used", which means inserting "AB" and "ABBA" will return true.
此解决方案无法验证字符“已被使用”,这意味着插入“ AB”和“ ABBA”将返回true。 If you need to do this, you just need to delete the verified char from the longer string in every loop.
如果需要这样做,则只需在每个循环中从较长的字符串中删除已验证的字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.