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; } }


Reply With Quote

Bookmarks