Return the length of the String that comes first lexicographically

154 views Asked by At

I am trying pass two strings to a function and I want to return the length of the string that comes first lexicographically.

This is what I have tried so far:

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;
    }
}
2

There are 2 answers

2
Spectric On BEST ANSWER

You can set them into an array, and use Arrays.sort(). Then retrieve the first item like so:

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();
    
}

Or you can use the .compareTo method like so:

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

Something to this effect should work I think.

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