Showing posts with label hackerrank. Show all posts
Showing posts with label hackerrank. Show all posts

Thursday, 17 November 2016

Palindrome Index - Algorithm Solution

import java.io.*;
import java.util.*;
public class Solution {
    public static void main(String[] args) throws IOException {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
         StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       
        for(byte T = Byte.parseByte(br.readLine()); T > 0; --T){
            final char[] C = br.readLine().toCharArray();
            final int N = C.length;
            int c = -1;
            for(int i = 0, j = N-1; i < j; ++i, --j){
                if (C[i] != C[j]){
                    c = isPalindrome(C, i+1, j+1) ? i : j;
                    break;
                }
            }
            sb.append(c + "\n");
        }
        System.out.print(sb);
    }
     private static boolean isPalindrome(final char[] C, final int A, final int B){
        for(int i = A, j = B-1; i < j; ++i, --j){
            if (C[i] != C[j]){
                return false;
            }
        }
        return true;
    }
   
}

The Love-Letter Mystery - Algorithm Solution in JAVA 8

import java.io.*;
import java.util.*;
public class Solution {
  public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int numTestCases = s.nextInt();
while (numTestCases > 0) {
String word = s.next();
System.out.println(getNumRotations(word));
--numTestCases;
}
s.close();
}
public static int getNumRotations(String word) {
char[] wordArr = word.toCharArray();
int count = 0;
int j = word.length() - 1;
for(int i = 0; i < wordArr.length / 2; i++, j--){
count += Math.abs((int)(wordArr[i] - wordArr[j]));
}
return count;
}
}