Alice's library

Alice is rearranging her library. She takes the innermost shelf and reverses the order of books. She breaks the walls of the shelf. In the end, there will be only books and no shelf walls. Print the order of books.

Opening and closing walls of shelves are shown by '/' and '\' respectively whereas books are represented by lower case alphabets.

Example:

Input:   s = "/u/love\\i\\"
Output: iloveu

Approach

Java

public class AliceSibrary {
    public static void main(String args[]) {

        String s = "/u/love\\i\\";

        while (s.charAt(0) == '/') {
            int x = 0, y = 0;
            for (int i = s.length() - 1; i >= 0; i--) {
                if (s.charAt(i) == '\\')
                    y = i;
                if (s.charAt(i) == '/') {
                    x = i;
                    break;
                }

            }

            s = s.substring(0, x) + reverse(s.substring(x + 1, y)) + s.substring(y + 1);
        }
        System.out.println(s);

    }

    public static String reverse(String str) {
        StringBuilder sb = new StringBuilder(str);
        sb.reverse();
        return sb.toString();
    }
}


No comments:

Post a Comment