gpt4 book ai didi

java - 如何检查一个字符串是否可以使用另一个字符串中的字符进行拼写?

转载 作者:行者123 更新时间:2023-12-02 09:31:02 24 4
gpt4 key购买 nike

示例:字符串 a = "ACAHBBA"和字符串 b = "ABAB"应返回 true,因为这两个字符串都可以拼写 ABAB。

我尝试过 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;
}
}

可能的解决方案?

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;
}

最佳答案

简单地迭代一个字符串并获取该字符的索引。如果 >= 0,则用非字母字符替换字符并重复。该算法假定需要匹配正确数量的字符。例如,如果字符集是 helohello 将返回 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;
}

关于java - 如何检查一个字符串是否可以使用另一个字符串中的字符进行拼写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57978985/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com