String Power

Helsinki never listens to the classes of The Professor. So Professor assigns a task to Helsinki. The task goes this way.. 
To each alphabet Professor assigned a value, i.e. a is assigned 0, b is assigned 1, …, and z is assigned 25. He gave a string consisting of lower case letters only. The power of the string is sum of values of all its characters. He asked Helsinki to find another string of same length and same power. If they are multiple strings find lexicographically least one. Help Helsini with the task. If no other string exists print power of string S and -1. If exists print power of S and other string
(same power of S and same length as S).

Example:

Input: s="abz"
Output: 26 acy

Approach

Java


public class StringPower {
    public static void main(String args[]) {
        char str[] = "abz".toCharArray();
        int pow = 0;
        for (int i = 0; i < str.length; i++) {
            pow += (int) (str[i] - 97);
        }
        if (pow == 0 || pow == (25 * str.length) || str.length == 1) {
            System.out.println(pow + " -1");
        }
        int i = 0;
        int k = 1;
        int change = 0;
        while (i < str.length - 1) {
            int x = 122 - (int) str[k];
            int p = (int) str[i] - 97;
            if (x >= p) {
                str[i] = 'a';
                change += p;
                str[k] = (char) ((int) str[k] + p);
                i++;
                k = i + 1;
            } else {
                str[i] = (char) ((int) str[i] - x);
                str[k] = (char) ((int) str[k] + x);
                change += x;
                k++;
            }
            if (k == str.length) {
                i++;
                k = i + 1;
            }
        }
        if (change == 0) {
            for (int j = str.length - 2; j >= 0; j--) {
                if (str[j] != 'z') {
                    str[j] = (char) ((int) str[j] + 1);
                    str[j + 1] = (char) ((int) str[j + 1] - 1);
                    break;
                }
            }
        }
        System.out.print(pow + " ");
        for (int j = 0; j < str.length; j++) {
            System.out.print(str[j]);
        }
        System.out.println();
    }
}


No comments:

Post a Comment