【问题标题】:Is string combination of substring?是子串的字符串组合吗?
【发布时间】:2019-09-25 14:33:02
【问题描述】:

给定两个字符串,如果大字符串是小字符串的组合,我的函数应该返回 true,否则返回 false。即

cat 和 catcatcatcat 会返回 true cat 和 catdogcatcat 会返回 false

我不确定为什么它不起作用,或者我的逻辑是否正确。

public static boolean isCat(String s, String y) {
    int yl= y.length();
    int counter= 0;    

    for (int i= 0; i < s.length(); i++ ) {
        char[] ychar= y.toCharArray();
        char[] subchar= s.substring(counter, counter + yl).toCharArray();
        if (Arrays.equals(ychar, subchar) == true) {
            counter+= yl;
            return true;
        }
    }
    return true;
}

【问题讨论】:

标签: java string


【解决方案1】:

一个更简单的方法是 replace() 带有空字符串的子字符串的所有实例,并检查结果字符串是否为空。

public class Test {
    public static void main(String[] args) {
        System.out.println(isCat("catcatcat", "cat")); // "true"
        System.out.println(isCat("cacatcatt", "cat")); // "false"
    }

    public static boolean isCat(String full, String sub) {
        return sub.isEmpty() || !full.isEmpty() && full.replace(sub, "").isEmpty();
    }
}

或者,使用正则表达式检查字符串matches()是否是子字符串的倍数:

public static boolean isCat(String full, String sub) {
    return full.matches("(\\Q" + sub + "\\E)+");
}

【讨论】:

  • 你能再解释一下吗?我试过了,它不起作用。什么是 \\Q 和 \\E。你在那条线上做什么?
  • \Q\E 开始和结束正则表达式中的引用部分。您尝试了哪些字符串?
  • String g= ""; String replaced= s.replace(y, ""); g+= replaced; return g.isEmpty(); }
  • 上面的代码除了大字符串为空小字符串为“x”的情况外都有效
  • 这是一个很好的观点。您只需要检查整个字符串是否为空即可解决这种情况。我会更新我的答案。
【解决方案2】:

最有效的方法是使用regionMatches:这允许您在不创建新字符串的情况下比较字符串区域:

int a;
for (a = 0; a < s.length(); a += y.length()) {
  if (!s.regionMatches(a, y, 0, y.length()) {
    break;
  }
}
return a == s.length();

regionMatches 实际上只是逐个字符地迭代;你可以用一个循环来写:

int a;
outer: for (a = 0; a < s.length(); a += y.length()) {
  if (a + y.length() > s.length()) break;
  for (int b = 0; b < y.length(); ++b) {
    if (s.charAt(a + b) != y.charAt(b)) break outer;
  }
}
return a == s.length();

你可以用一个循环来写它:

int a = 0;
for (a = 0; a < s.length(); ++a) {
  if (s.charAt(a) != y.charAt(a % y.length()) break;
}
// You could put a check for s.length() % y.length() first,
// since there is no point in looping if that is non-zero
return a == s.length() && (a % y.length()) == 0;

【讨论】:

    猜你喜欢
    • 2011-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-30
    相关资源
    最近更新 更多