【问题标题】:Compare two strings and return true if one string contains all characters of other one比较两个字符串,如果一个字符串包含另一个字符串的所有字符,则返回 true
【发布时间】:2015-11-08 03:46:52
【问题描述】:

我正在练习 lintcode 并试图解决这个问题

比较两个字符串A和B,判断A是否包含B中的所有字符。

字符串 A 和 B 中的字符都是大写字母。

我编写了这段代码,它检查 A 中 B 的每个字符并从 A 中消除找到的字符,但不知何故它未能通过输入测试 A = "ABCD" 和 B = "ACC" 。当它应该给出假时,它给出的输出为真

我不明白我的代码中的问题

    public class Solution {
/**
 * @param A : A string includes Upper Case letters
 * @param B : A string includes Upper Case letter
 * @return :  if string A contains all of the characters in B return true else return false
 */
public boolean compareStrings(String A, String B) {
    // write your code here
    int aLen = A.length();
    int bLen = B.length();
    if (aLen == 0) {
        return bLen == 0;
    }
    for(int i = 0; i<bLen; i++){
        String temp = B.substring(i,i);
        if(A.contains(temp))
            A.replace(temp, "");
        else
            return false;
    }
    return true;
}

}

【问题讨论】:

  • 字符串AAA 的结果应该是什么?
  • 主要问题是A.replace(temp, "");应该是A = A.replace(temp, "");。我同意 Pshemo,问题也可以更清楚。
  • @PaulBoddington 我试过了。还是不行
  • @Pshemo 据我了解的问题,对于输入 A,AA,输出应该是 false
  • 提示:尝试打印temp

标签: java string compare


【解决方案1】:

String 类的 replace() 方法将用第二个参数替换每个出现的第一个参数,请尝试使用 replaceFirst() 代替。示例实现

    public static boolean compareStrings(String A, String B) {
            boolean isOk = true;

            for (int i = 0;i < B.length();i++) {
                    if (!A.contains(B.charAt(i) + "")) {
                        isOk = false;
                        break;
                    }
                    A = A.replaceFirst(B.charAt(i) + "", ""); 
            }
            return isOk;
    }

【讨论】:

  • 感谢您的回复
【解决方案2】:

您每次只想从A 中删除一个字符。否则下次遇到B中的同一个字符就不会出现了。

尝试使用replaceFirst 而不是replace

您还需要使用A = A.replaceFirst(...) 将结果分配回A,否则您实际上不会更改String

最后,B.substring(i,i); 是一个长度为0 的字符串,而不是一个长度为1 的字符串。请改用"" + B.charAt(i)B.substring(i, i + 1)

这是一个完整的版本

public static boolean compareStrings(String A, String B) {
    // write your code here
    int aLen = A.length();
    int bLen = B.length();
    if (aLen == 0) {
        return bLen == 0;
    }
    for(int i = 0; i<bLen; i++){
        String temp = B.substring(i,i + 1);
        if(A.contains(temp))
            A = A.replaceFirst(temp, "");
        else
            return false;
    }
    return true;
}

【讨论】:

  • 我尝试了你的两个建议。没有任何影响。
  • 是的,我的原始代码是这个 B.substring(i, i + 1) 但它不起作用
  • @SadiqHusainKhan 你能举个例子说明这 3 项更改不起作用吗?
  • B.substring(i, i + 1) 不适用于输入:“A”、“”错误:索引超出范围
  • @SadiqHusainKhan 这是不正确的。如果B""bLen0,所以甚至不会进入循环。我认为问题在于您发布的代码不是您使用的实际版本。
猜你喜欢
  • 2015-05-13
  • 1970-01-01
  • 2018-04-23
  • 1970-01-01
  • 1970-01-01
  • 2013-04-08
  • 2012-12-16
  • 1970-01-01
  • 2020-09-03
相关资源
最近更新 更多