Java比较数组中的字符串

时间:2015-01-23 08:47:49

标签: java arrays string sorting

给定一个字符串数组,返回具有最多数字的字符串,紧跟字母x后面。如果两个字符串具有相同的数字,则返回索引最低的字符串。

gooD({"1x","123456789","1y3534ssf","4hsd73s"}) → "1x"
gooD({"1xs3x3412fgxx6","1x+4x=5x","x5x"}) → "1x+4x=5x"
gooD({"3x2y11x3gx5x","","232","2x2xx3x3x"}) → "2x2xx3x3x"

我完全不知道为什么我的代码无效。为什么这样?

public String gooD(String arr[]) {
    String digits="0123456789";
    int low=0;
    int check=0;
    String s="";
    String d="";
    for (int i=0; i<arr.length; i++) {
        s=arr[i];
        for (int j=0; j<s.length()-1; j++) {
            if (digits.indexOf(s.substring(j,j+1))!=-1) {
                    if (s.substring(j+1,j+2).equals("x")) {
                        d+=s.substring(j,j+1);
                    }
            }
        }
        check=d.length();
        if (check<low) low=check;
        d="";
    }
    for (int i=0; i<arr.length; i++) {
        s=arr[i];
        for (int j=0; j<s.length()-1; j++) {
            if (digits.indexOf(s.substring(j,j+1))!=-1) {
                    if (s.substring(j+1,j+2).equals("x")) {
                        d+=s.substring(j,j+1);
                    }
            }
        }
        if (d.length()==low) return d;
        d="";
    }
    return d;
}

3 个答案:

答案 0 :(得分:2)

一个错误是

if (check<low) low=check;

应该是

if (check > low) low = check;

因为你正在寻找最大值。

相当简单:

public static String gooD(String... arr) {
    int max = 0;
    String best = "";
    for( String s: arr ){
        String t = s.replaceAll( "\\dx", "" );
        int d = s.length() - t.length();
        if( d > max ){
            max = d;
            best = s;
        }
    }
    return best;
}

答案 1 :(得分:0)

@laune说的话。无论如何,这将更有效率

public String gooD(String arr[]) {
    Pattern pattern = Pattern.compile("\\dx");

    String candidate = "";
    int max = 0;
    for (String s : arr){
        Matcher matcher = pattern.matcher(s);
        int current = 0;
        while (matcher.find()){
            current++;
        }
        if (current > max){
            max = current;
            candidate = s;
        }
    }
    return candidate;
}

答案 2 :(得分:0)

首先,你必须改变你的测试:

    if (check<low) low=check;

应该是:

    if (check>low) low=check;

您的代码正在寻找最小值而不是最大值。

接下来,您没有返回输入数组,只返回了x后面的数字。

保持您的方法,可能的实施方式可能是:

public String gooD(String arr[]) {
    String digits = "0123456789";
    int low = 0;
    int ilow = 0; // first string by default
    int check = 0;
    String s;
    String d = "";
    for (int i = 0; i < arr.length; i++) {
        s = arr[i];
        check = 0;
        for (int j = 0; j < s.length() - 1; j++) {
            if (digits.indexOf(s.substring(j, j + 1)) != -1) {
                if (s.substring(j + 1, j + 2).equals("x")) {
                    check += 1;
                }
            }
        }
        if (check > low) { // only is strictly longer
            low = check;
            ilow = i; // keep the index of first longer string
        }
    }
    return arr[ilow]; // return the string
}
相关问题