Labels

Showing posts with label Palindrome. Show all posts
Showing posts with label Palindrome. Show all posts

Tuesday, 15 January 2013

Programming Interview Questions

Programming Interview Questions

Below programs written in Java but you can use your favorite programming language drive the results.

Scenario #1:
You are given a linked list with nodes containing characters. The number of characters in each node might differ
Question: Check if the data stored in the linked list is a palindrome?



import java.util.*;

public class LList {

public boolean isPal(List<String> ll){
String forward = "";
String bacward = "";

for (int i=0; i < ll.size();i++)
{
forward  = forward + ll.get(i);
bacward = bacward + reverse(ll.get(ll.size()-1-i));

}

System.out.println("Forward:"+forward);
System.out.println("Backward:"+bacward);
if (forward.equalsIgnoreCase(bacward)){
return true;
}
return false;
}

public String reverse(String ss){
String rev="";
for (int i=(ss.length()-1); i >= 0 ; i--){
rev = rev + ss.charAt(i);
}
return rev;
}
public static void main(String args[]){
List<String> ll = new LinkedList<String>();
ll.add("su");
ll.add("n");
ll.add("us");
LList l = new LList();
System.out.println("List is:"+ ll);
System.out.println("Is palindrome:"+ l.isPal(ll));
}
}



Result is:
List is:[su, n, us]
Forward:sunus
Backward:sunus
Is palindrome:true

Scenario #2:
Reverse the given string as well as reverse individual word in a sentence.

import java.util.*;

public class StringRev {
public String reverseString(String s) {
        if (s.length() <= 1) {
            return s;
        } 
        return reverseString(s.substring(1,s.length())) + s.charAt(0);
    }
public static void main(String args[]){
String str ="I love India";
System.out.println("Given string is:"+ str);
String word = "";
List<String> ll = new LinkedList<String>();
StringRev sr = new StringRev();
System.out.println("Entire string reverse:"+sr.reverseString(str));
for (int i=0; i< str.length();i++){
if (str.charAt(i)!=' '){
word = word + str.charAt(i);
} else{
ll.add(word);
word = "";
}
if (i == str.length()-1){
ll.add(word);
}
}
String backward = "";
for (int i=0; i < ll.size();i++){
backward  = backward +' ' +sr.reverseString(ll.get(i));
}
System.out.println("Individual word string reverse:"+backward);
}
}

Output is:
Given string is:I love India
Entire string reverse:aidnI evol I
Individual word string reverse: I evol aidnI