0

My assignment is to see if a string is a palindrome, so I was just going to use a for loop and add each character at i to the new string, and then the next pass through the loop the next character will be placed at [0] and all the other elements will be pushed back 1 spot, so at the end the new string will be the reverse of the input string, and I'll then compare the two strings and if they are = then it will print out "It's a palindrome!", otherwise it will print out "It isn't a palindrome".

I'm not allowed to use a string reverse method, I need to reverse the string myself. I have searched all over and I cannot find an answer to this.

Here is the code I have so far:

class PrimaryClass{

Scanner str = new Scanner(System.in);

String palindrome(String str){

    str.toCharArray();
    char[] arr = new char[str.length()];
    String reverse = "";

    for (int i = str.length(); i >= 0; i--){

    }



    return str;
}

At whatever the index is, I need to place the character that is at that index into the string 'reverse', and push all the other characters back.

  • 3
    This might help: http://stackoverflow.com/search?q=[java]+string+palindrome – Tom Apr 16 '15 at 19:25
  • Check this:http://stackoverflow.com/questions/7569335/reverse-a-string-in-java. Also, there are better ways to do this task were you don't need to create another copy of the string. – George Apr 16 '15 at 19:25
  • 1
    1 hint: You do not need to reverse your string to test if it's a palindrome. There's a better way to do it – ControlAltDel Apr 16 '15 at 19:25
  • 1
    Duplicate of here it appears and already solved: http://stackoverflow.com/questions/8444710/easiest-way-to-check-if-a-string-is-palindrome – Jeffrey Shackelford Apr 16 '15 at 19:32

6 Answers6

1

You have to think about this not in terms of 'pushing' the characters back. But rather either creating a new character array and swapping them around and then compare, or using a string. Although, strings are immutable in Java, when you add to a string, a new string is actually created and your variable now points to that. So for your purposes it doesn't matter. Granted, it is inefficient to keep making new strings and concatenating to it

Reversing a character array (that was a string) is done like so, as you said, a for loop.

 for ( int i = length - 1; i >= 0; i-- )
     reverse = reverse + original.charAt(i); //inefficient concatenation.

After which you just have to compare reverse and original, both are strings, done by original.equals(reverse)

Are you sure you tried to look for a solution? this is the first link on Google, which is apt for begineers.

On a different note (if you're doing data structures), you can also use a stack to check if a string is a palindrome, first by making it a char array, and then pushing each character onto the stack, then popping it again and comparing each character as you go. This might be an interesting approach for you to explore.

Lastly, reversing a string is a common programming interview question, especially in-place reversals that don't use extra memory. Something you might want to know, so keep in mind that it's easy to find solutions, but to actually implement them yourself in an interview, you got to learn the basics of how it all works by coming up with the algorithm yourself. Just additional info.

matrixanomaly
  • 6,627
  • 2
  • 35
  • 58
  • 2
    the compiler optimizes "bad" String concatenations – duffy356 Apr 16 '15 at 19:30
  • @duffy356 interesting. do you have a source for this? I'll check it out soon. – matrixanomaly Apr 16 '15 at 19:30
  • but not every compiler does this. try it out – duffy356 Apr 16 '15 at 19:31
  • here is a reference: https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.18.1 – duffy356 Apr 16 '15 at 19:37
  • @duffy356 Not sure how I can try it out, but inconclusive research tells me that it won't work in a loop: http://stackoverflow.com/questions/1532461/stringbuilder-vs-string-concatenation-in-tostring-in-java ... Oracle JDK doesn't handle it: http://www.javacodegeeks.com/2013/03/java-stringbuilder-myth-debunked.html and http://stackoverflow.com/questions/11311234/java-compiler-doesnt-optimize-string-concatenation-automatically it might not always be the case – matrixanomaly Apr 16 '15 at 19:38
  • @duffy356 just saw your Java 8 link, thanks! Though I've been doing concatenation with + ever since I started programming in java (professors don't tell you it's bad too), so... maybe it's good to note that string builder is better for cases where performance is critical. – matrixanomaly Apr 16 '15 at 19:40
0

It's inefficient to build a copy of a String to solve this problem. A smarter solution would be to use a single loop to inspect the first and last character of a String, then the second-from-first and second-to-last, and so on, returning false if any pair of characters does not match, and true if they all match.

Don't forget to stop halfway, because it's inefficient to do the exact same checks twice. And don't forget that an odd number of characters will mean that the middle character can be anything as it's not paired with anything else.

Bobulous
  • 12,967
  • 4
  • 37
  • 68
0

You should assign char[] arr = str.toCharArray(); and the loop would be

for (int i = str.length(); i > 0; i--){
    reverse += arr[i-1]
}

and finally reverse will have the reversed string.

Sandeep Poonia
  • 2,158
  • 3
  • 16
  • 29
0

Here is what Bobulous is talking about, using no temp array :

public class Test {
  public static void main(String[] args) {
    if(args.length != 1) {
      System.out.println("Please provide a string to check for palindrome.");
      return;
    }

    System.out.format("Is \"%s\" a palindrome ? : %b\n", args[0], isPalindrome(args[0]));

  }

  private static boolean isPalindrome(String string) {
    int forwardI = 0;
    int backwardI = string.length()-1; // last character
    while(forwardI < backwardI) {
      if(string.charAt(forwardI++) != string.charAt(backwardI--)) {
        return false;
      }
    }
    return true;
  }
}

Now you own me a beer. And one to Bobulous :)

baraber
  • 3,296
  • 27
  • 46
0

You want to check if string is palindrome? Try this:

public static boolean isPalindrome(String str) {
    return str.equals(new StringBuilder(str).reverse().toString());
}

Another solution:

public static boolean isPalindrome(String str){
    char[] word = str.toCharArray();
    int i1 = 0;
    int i2 = word.length - 1;
    while (i2 > i1) {
        if (word[i1] != word[i2]) {
            return false;
        }
        ++i1;
        --i2;
    }
    return true;
}
Eldar Agalarov
  • 4,849
  • 4
  • 30
  • 38
  • He mentionned : "I'm not allowed to use a string reverse method" I think StringBuilder's reverse method is probably not allowed eighter :P – baraber Apr 16 '15 at 19:53
0

If you are just looking to reverse the characters of the string before testing for a palindrome, try concatenating the string letter by letter backwards into a new variable.

Like so:

var word = "Hello World"
var palindrome = ""
for ( i = word.length - 1 ; i >= 0 ; i-- ){
palindrome = palindrome + word[i];
}

This should work nicely if doing a test for equal strings between the two variables... in my case the string is not a palindrome. :)

Crash
  • 1
  • 2