(UVA) Mother Bear - Solution

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

In order to discover if the sentence is a palindrome, the characters are compared ignoring those that are not valid.


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

class Main {
    public void process() throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        HashSet<Character> notValid = new HashSet<>();
        notValid.add('.');
        notValid.add(',');
        notValid.add('!');
        notValid.add('?');
        notValid.add(' ');
        
        String line = br.readLine();
        while (!line.equals("DONE")) {
            line = line.toUpperCase();
            boolean palindrome = true;
            for (int i = 0, j = line.length()-1; i < j; i++, j--) {
                while (notValid.contains(line.charAt(i))) { // if the current char is not valid
                    i++;
                }
                while (notValid.contains(line.charAt(j))) { // if the current char is not valid
                    j--;
                }
                if (line.charAt(i) != line.charAt(j)) {
                    palindrome = false;
                    System.out.println("Uh oh..");
                    break;
                }
            } 
            if (palindrome) {
                System.out.println("You won't be eaten!");
            }
            
            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