-1

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

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

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

所以这里是代码:

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。这正是我在代码中想要的结果,但我想知道它为什么会发生。匹配方法是否测试以确保每个数字只匹配一次?

谢谢!

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

4

2 回答 2

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]"));

查看实际返回值。

于 2017-01-30T04:59:29.633 回答
0

从理论上讲,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]"))

于 2017-01-30T05:06:08.200 回答