• + 0 comments

    Java

    public static String biggerIsGreater(String w) {
            char[] charArray = w.toCharArray();
            int n = charArray.length;
    
            // Step 1: Find the rightmost character that is smaller than its next character
            int index = -1;
            for (int i = n - 2; i >= 0; i--) {
                if (charArray[i] < charArray[i + 1]) {
                    index = i;
                    break;
                }
            }
    
            // If no such character exists, it's the last permutation
            if (index == -1) {
                return "no answer";
            }
    
            // Step 2: Find the smallest character on the right of `index` that is larger than charArray[index]
            int switchIndex = -1;
            for (int i = n - 1; i > index; i--) {
                if (charArray[i] > charArray[index]) {
                    switchIndex = i;
                    break;
                }
            }
    
            // Step 3: Swap the characters at `index` and `switchIndex`
            char temp = charArray[index];
            charArray[index] = charArray[switchIndex];
            charArray[switchIndex] = temp;
    
            // Step 4: Sort the substring after `index` to get the next lexicographical order
            Arrays.sort(charArray, index + 1, n);
    
            return new String(charArray);
        }