0

这是我到目前为止所做的递归,但它似乎不正确,这主要是出于兴趣。任何帮助或提示将不胜感激。

public class CompareStrings { 
    public static boolean match(String x, String y) {
        //turn each string into a char[], sort that array,
        //then compare the two Simple 
        char[] first  = x.toCharArray();
        char[] second = y.toCharArray();
        java.util.Arrays.sort(first);
        java.util.Arrays.sort(second);
        String sorted_str1 = new String(x);
        String sorted_str2 = new String(y);

        if(sorted_str1.equals(sorted_str2)){
            return true;
        }
        else{
            return false;
        }

    } 

    public static void main(String args[]) { 
        System.out.println(match("hello", "hello.")); // should return false
        System.out.println(match("hello", "jello")); // should return false
        System.out.println(match("hello", "h@llo")); // should return true
        System.out.println(match("hello", "h@@@@")); // should return true
        System.out.println(match("hello", "h*")); // should return true
        System.out.println(match("hello", "*l*")); // should return true
        System.out.println(match("anyString", "*")); // should return true
    }
}
4

2 回答 2

1

你必须记住,如果你想使用递归,你必须在函数内部使用你的函数。看看和例子:

void myMethod( int counter)
{
if(counter == 0)
else
{
System.out.println("hello" + counter);
myMethod(--counter);
System.out.println(""+counter);
}
} 

我的函数是 myMethod,我在它自己内部使用它。但是你没有这样做,所以你没有使用Recursion

于 2013-03-30T17:29:14.827 回答
1

我不知道递归,但为什么不做一些简单的事情

public static boolean match(String x, String y) {
    return x.matches(y.replace("@", ".").replace("*", ".*"));
}

在正则表达式中,

  • .匹配任何字符
  • X*匹配X 0 次或多次
  • 因此,.*匹配任何字符串,包括空字符串

Judging by your examples, you want @ to match a single character and * to match any string. So, we replace all @s in y with . and replace all *s with .*, and use the resulting string as a regular expression, checking if x matches it.


System.out.println(match("hello", "hello."));
System.out.println(match("hello", "jello"));
System.out.println(match("hello", "h@llo"));
System.out.println(match("hello", "h@@@@"));
System.out.println(match("hello", "h*"));
System.out.println(match("hello", "*l*"));
System.out.println(match("anyString", "*"));
false
false
true
true
true
true
true
于 2013-03-30T17:34:08.753 回答