CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 9 of 9
  1. #1
    Join Date
    Feb 2013
    Posts
    3

    Finding if a Palindrom - Please review

    Hi, I am a Java newbie and I am working on this piece of code to figure out if a string is a palindrom or not. Could some experts review my code and provide comments on how I could have done it better, if at all? Also, even for this simple program I am using a separate class because I am planning to add more practice problems to my collection in their own classes. Didn't want clutter up one main class. Any help is appreciated. Thanks in advance.

    Code:
    public class PracticeProbs {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Palindrome p = new Palindrome("NOTAPALINDROME");
    		
    		System.out.println("Is palindrome: " + p.isPalindrome()); // prints false for NOTAPALINDROME, true for RACECAR
    	}
    }
    
    import org.apache.commons.lang3.ArrayUtils;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Stack;
    
    public class Palindrome {
    	private Character[] s;
    	private List<Character> sRev = new ArrayList<Character>();
    	// Checks if a string is a palindrome
    	
    	public Palindrome(String in){
    		s = ArrayUtils.toObject(in.toCharArray());
    	}
    	
    	boolean isPalindrome(){
    		Stack<Character> stackRevStr = new Stack<Character>();
    		
    		for(int i=0;i<s.length; i++){
    			stackRevStr.push(Character.valueOf(s[i]));
    		}
    		
    		for(int i=0;i<s.length; i++){
    			while (!stackRevStr.isEmpty()) {
    				sRev.add(stackRevStr.pop());
    			}
    		}
    		
    		int i = 0;
    
    		for(Character c: sRev){
    			if(!c.equals(s[i])){
    				return false;
    			}
    			i++;
    		}
    		return true;
    	}
    }

  2. #2
    Join Date
    Aug 2011
    Location
    West Yorkshire, U.K.
    Posts
    54

    Re: Finding if a Palindrom - Please review

    You could make isPalindrome() take a String argument, and make it static. That way you don't need to create an instance of the Palindrome class in main.
    Code:
        public static void main(String args[]) {
            String test = "HELLOWORLD";
            boolean res = Palindrome.isPalindrome(test);
            System.out.println(test + " => " + res);
            ... etc
    Java's StringBuilder provides a facility to reverse a String ... so your isPalindrome() function could easily be reduced to:
    Code:
        public static boolean isPalindrome(String inp) {
            StringBuilder sb = new StringBuilder(inp);
            sb.reverse();
            return inp.equalsIgnoreCase(sb.toString());
        }

  3. #3
    Join Date
    Feb 2013
    Posts
    3

    Re: Finding if a Palindrom - Please review

    Thanks for your reply. I needed an implementation for a better understanding of the language though.

  4. #4
    Join Date
    Aug 2011
    Location
    West Yorkshire, U.K.
    Posts
    54

    Re: Finding if a Palindrom - Please review

    OK - if you want to do it without using "built in" functions, then you could create a character array from the original string, another character array to hold the revered string, populate it and then test it character by character thus:
    Code:
        private static boolean isPalindrome(String test) {
            boolean returnValue = true;
    
            // Create character array from input String
            char input[] = test.toCharArray();
    
            // Create character array to hold reversed input
            char reversed[] = new char[input.length];
    
            // Populate reversed array
            for(int i=0; i<input.length; i++) {
                reversed[(input.length - (i + 1))] = input[i];
            }
    
            // Check that reversed array is the same as input array
            for(int i = 0; i < input.length; i++) {
                if (input[i] != reversed[i]) {
                    returnValue = false;
                    break;
                }
            }
    
            return returnValue;
        }
    I appreciated that you are trying to understand the fundamentals of the language ... but sometimes it is better to use functions that have already been written and tested rather than trying to re-invent the wheel yourself!

  5. #5
    Join Date
    May 2009
    Location
    Lincs, UK
    Posts
    298

    Re: Finding if a Palindrom - Please review

    I would just use a for loop, going from 0 to half the length of the string, using it as an offset from both ends of the string and compare the characters in those positions. You can stop when the characters in one of these pairs are different (the string is not a palindrome); if you get to the centre of the string and all of the pairs were equal the string is a palindrome. The only methods you need to do this are length() and charAt() and there is no need to instantiate other objects.

  6. #6
    Join Date
    Aug 2011
    Location
    West Yorkshire, U.K.
    Posts
    54

    Re: Finding if a Palindrom - Please review

    Quote Originally Posted by jcaccia View Post
    I would just use a for loop, going from 0 to half the length of the string, using it as an offset from both ends of the string and compare the characters in those positions. You can stop when the characters in one of these pairs are different (the string is not a palindrome); if you get to the centre of the string and all of the pairs were equal the string is a palindrome. The only methods you need to do this are length() and charAt() and there is no need to instantiate other objects.
    Good point.

  7. #7
    Join Date
    Feb 2013
    Posts
    1

    Re: Finding if a Palindrom - Please review

    Code:
    import java.util.Scanner;
    import java.util.Stack;
    
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    public class Pln {
    public static void main(String...args){
    System.out.println("Enter Word ")	;
    String s=new Scanner(System.in).nextLine();
    String h = "",ss="",ori=s;
    	 
    for(int i=0;i<s.length();i++){
    	char c=s.charAt(i);
    	if (Character.isDigit(c)||Character.isLetter(c))
    	{	
    		ss+=s.charAt(i);
    }	
    	
    }	
    	
    	
    	;	
    for(int i=0;i<s.length();i++){
    	char c=s.charAt(s.length()-i-1);
    	if (Character.isDigit(c)||Character.isLetter(c))
    		h+=s.charAt(s.length()-i-1);
    	 
    
    	}
    if(ss.equalsIgnoreCase(h))System.out.println("PALINDROME "+ori);
    else{
    	System.out.println("NOT PALINDROME "+ori);	
    }
    }
    static{
    	
    	JOptionPane.showMessageDialog(new JFrame(), "stat");
    }
    Pln(){
    	
    	JOptionPane.showMessageDialog(new JFrame(), "x");
    
    }
    }

  8. #8
    Join Date
    Feb 2013
    Posts
    3

    Re: Finding if a Palindrom - Please review

    Thank you all for your comments. This is what I finally came up with. Please review and share your thoughts.

    Code:
    boolean isPalindromAnother() {
    
    		// Store the length of input
    		int len = s.length;
    
    		for (int i = 0, j = len - 1; i <= len / 2; i++, j--) {
    			if (s[i] != s[j])
    				return false;
    		}
    
    		return true;
    	}

  9. #9
    Join Date
    Jan 2009
    Posts
    596

    Re: Finding if a Palindrom - Please review

    Remember to always check the code works for corner cases. For example, what will this code do for a zero-length string? Hint: it will try to access an invalid index.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured