(UVA) Palindromes - Solution

Link to the problem: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=342

The solution below keeps a map that associates a character with its mirror character, which we use to check if the entry is a mirrored string. Moreover, it is also checked if the entry is a regular palindrome. Then, the answer is given according to the fulfilled properties.


import java.io.*;
import java.util.*;

class Main {
    public HashMap<Character, Character> reverse;
    
    public void initMap() {
        reverse.put('A', 'A');
        reverse.put('E', '3');
        reverse.put('H', 'H');
        reverse.put('I', 'I');
        reverse.put('J', 'L');
        reverse.put('L', 'J');
        reverse.put('M', 'M');
        reverse.put('O', 'O');
        reverse.put('S', '2');
        reverse.put('T', 'T');
        reverse.put('U', 'U');
        reverse.put('V', 'V');
        reverse.put('W', 'W');
        reverse.put('X', 'X');
        reverse.put('Y', 'Y');
        reverse.put('Z', '5');
        reverse.put('1', '1');
        reverse.put('2', 'S');
        reverse.put('3', 'E');
        reverse.put('5', 'Z');
        reverse.put('8', '8');
    }
    
    public void process() throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        reverse = new HashMap<>();
        initMap();
        
        String line = br.readLine();
        while (line != null) {
            boolean mirror = true;
            boolean palindrome = true;
            for (int i = 0, j = line.length()-1; i <= j; i++, j--) {
                if (line.charAt(i) != line.charAt(j)) {
                    palindrome = false;
                }
                if (!reverse.containsKey(line.charAt(i)) || (reverse.containsKey(line.charAt(i)) && reverse.get(line.charAt(i)) != line.charAt(j))) {
                    mirror = false;   
                }
            }        
            
            if (palindrome && mirror) {
                System.out.println(line + " -- is a mirrored palindrome.\n");
            }
            else if (palindrome) {
                System.out.println(line + " -- is a regular palindrome.\n");
            }
            else if (mirror) {
                System.out.println(line + " -- is a mirrored string.\n");
            }
            else {
                System.out.println(line + " -- is not a palindrome.\n");
            }
            
            line = br.readLine();
        }
                       
        return;
    }
    
    public static void main(String[] args) throws NumberFormatException, IOException {
        Main m = new Main();
        m.process();
        
        System.exit(0);
    }
}

Comments

Popular posts from this blog

(Coderbyte) Powers of Two - Solução

(Coderbyte) Dash Insert II - Solução

(CoderByte) Number Search - Solução