Search code examples
javalexicographic

Return the length of the String that comes first lexicographically


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

Solution

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