【问题标题】:Avoid matching the same value twice in string.matches() method in Java避免在 Java 中的 string.matches() 方法中两次匹配相同的值
【发布时间】:2017-06-15 04:56:13
【问题描述】:

好的,我完全重写了这个问题,因为它有效,我想知道它为什么有效。

假设我有一个数字 testNumber,值为 567。

我想知道接下来的两个数字(shouldPassTest 和 shouldFailTest)是否相同,但在不同的 10s 位置。

代码如下:

int testNumber = 567;
int num1 = 5;
int num2 = 6;
int num3 = 7;

int shouldPassTest = 756; 
int shouldFailTest = 777;


if(Integer.toString(shouldPassTest).matches("[5,6,7][5,6,7][5,6,7]")
{
    //Do some cool stuff
}

if(Integer.toString(shouldFailTest).matches("[5,6,7][5,6,7][5,6,7]")
    {
        //Do some cool stuff
    }

当您运行该程序时,会从可用数字范围(5、6 和 7)中测试每个数字。从理论上讲,shouldFailTest 实际上应该通过测试,看看 7 如何符合我的三个标准之一,尽管是 3 次。

但发生的情况是 777 在测试时返回 false。这正是我在代码中想要的结果,但我想知道为什么会发生。匹配方法是否测试以确保每个数字只匹配一次?

谢谢!

这篇文章经过高度编辑。运行我的代码后,我发现该方法完全符合我的要求,但现在我想知道为什么。谢谢。

【问题讨论】:

  • 听起来您正在查看一个数字是否是另一个数字的字谜。
  • “不同的解决方案”。使用Integer.toString 后,将字符串分解为字符,并使用数组来保存字符。然后你可以从数组中删除东西。更好的是使用Set,但如果您的号码可以有多个相同的数字,那将无法正常工作。但不要试图用正则表达式来解决这个问题。
  • 是的,奇怪的是,代码完全符合我的要求。 777 返回错误。现在我既惊喜又困惑。
  • 其实 777 不会返回 false。您正在检查 Integer.toString(shouldFailTest).matches("[5,6,7][5,6,7][5,6,7]") 在上面的代码中是否返回 true。
  • 您摘录的代码甚至无法编译,因为您的 if 语句中的括号不平衡。

标签: java overlapping-matches


【解决方案1】:

我会使用以下内容,因为正则表达式不是解决这个问题的好方法:

public class Count {
    private int value;
    public Count() {
        value=0;
    }
    void increment() {
        value++;
    }
    void decrement() {
        value--;
    }

    public int getValue() {
        return value;
    }
}
public static boolean isAnagram(int val1, int val2) {
    Map<Character, Count> characterCountMap=new HashMap<>();
    for(char c:Integer.toString(val1).toCharArray()) {
        Count count=characterCountMap.get(c);
        if(count==null) { count=new Count(); characterCountMap.put(c, count);}
        count.increment();
    }
    for(char c:Integer.toString(val2).toCharArray()) {
        Count count=characterCountMap.get(c);
        if(count==null) { return false; }
        else { count.decrement(); }
        if(count.getValue()==0) {
            characterCountMap.remove(c);
        }
    }
    return characterCountMap.size()==0;
}

请运行:

System.out.println(Integer.toString(shouldFailTest).matches("[5,6,7][5,6,7][5,6,7]"));

查看实际返回值。

【讨论】:

    【解决方案2】:

    理论上,shouldFailTest 实际上应该通过测试,如下所示 7 如何符合我的三个标准之一,尽管是 3 次。

    但发生的情况是 777 在测试时返回 false。这是 正是我在代码中想要的结果,但我想知道为什么 发生了。匹配方法是否测试以确保每个数字 只匹配一次?

    不,“777”确实匹配您指定的模式“[5,6,7][5,6,7][5,6,7]”

    您的代码中的以下条件将评估为真。

    if(Integer.toString(shouldFailTest).matches("[5,6,7][5,6,7][5,6,7]"))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-27
      • 2013-04-28
      • 2013-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多