返回按字典顺序出现的String的长度

问题描述

我正在尝试将两个字符串传递给一个函数,我想按字典顺序返回第一个字符串的长度。

这是我到目前为止尝试过的:

public static int problem4(String s,String t) {
    for (int i = 0; i < s.length() &&
            i < t.length(); i++) {
        if ((int) s.charat(i) ==
                (int) t.charat(i)) {
            continue;
        } else {
            return (int) s.length() -
                    (int) t.length();
        }
    }

    if (s.length() < t.length()) {
        return (s.length() - t.length());
    } else if (s.length() > t.length()) {
        return (s.length() - t.length());
    }

    // If none of the above conditions is true,// it implies both the strings are equal 
    else {
        return 0;
    }
}

解决方法

您可以将它们设置为数组,然后使用Arrays.sort()。然后像这样检索第一个项目:

public static int problem4(String s,String t) {
    String[] items = new String[2];
    items[0]=s;
    items[1]=t;
    items.sort();
    return items[0].length();
    
}

或者您可以像这样使用.compareTo方法:

public static int problem4(String s,String t) {
    return s.compareTo(t) > 0 ? t.length() : s.length();
 }
,

这种效果应该可以解决。

public static int problem4(String s,String t){
    if (s.compareTo(t)>0)
        System.out.println(t.length());
        return t.length();
    else 
        System.out.println(s.length());
        return s.length();
}

problem("a","b");