Monday, December 2, 2002

P A L I N D R O M E

package org.interview.test;

import java.util.Scanner;

public class Palindrome {

public static void main(String [] args) throws Exception {
String original , reverse = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter:" );
original = sc.next();

int length = original.length();

System.out.println("Length:"+length);

for(int i =length-1; i >= 0; i--) {
reverse = reverse + original.charAt(i);
}

System.out.println("Reverse:"+ reverse);

if(original.equals(reverse)) {
System.out.println(original+" - is palindrome of - " + reverse);
}
}

}
= = = = = = = = = = = = = = = = = Reverse String recursive and iterative = = = = = = = = = = = = = = = = = = = = = 
package com.test;

import java.io.FileNotFoundException;
import java.io.IOException;

public class StringReverseExample {

    public static void main(String args[]) throws FileNotFoundException, IOException {

        //original string
        String str = "Sony is going to introduce Internet TV soon";
        System.out.println("Original String: " + str);

        //reversed string using Stringbuffer
        String reverseStr = new StringBuffer(str).reverse().toString();
        System.out.println("Reverse String in Java using StringBuffer: " + reverseStr);

        //iterative method to reverse String in Java
        reverseStr = reverse(str);
        System.out.println("Reverse String in Java using Iteration: " + reverseStr);

        //recursive method to reverse String in Java
        reverseStr = reverseRecursively(str);
        System.out.println("Reverse String in Java using Recursion: " + reverseStr);

    }

    public static String reverse(String str) {
        StringBuilder strBuilder = new StringBuilder();
        char[] strChars = str.toCharArray();

        for (int i = strChars.length - 1; i >= 0; i--) {
            strBuilder.append(strChars[i]);
        }

        return strBuilder.toString();
    }

    public static String reverseRecursively(String str) {

        //base case to handle one char string and empty string
        if (str.length() < 2) {
            return str;
        }

        return reverseRecursively(str.substring(1)) + str.charAt(0);

    }
}

No comments:

Post a Comment