-4

Possible Duplicate:
Check string for palindrome

Hello experts. I am asked, if it is possible to find whether a string is palidrome of another string in just one line of code in C++/Java.

If yes, then how?

Can any one answer. Thnx for ur view.

Community
  • 1
  • 1
Stuti
  • 1,620
  • 1
  • 16
  • 33
  • 2
    Have you tried reversing one of the strings? – Joe Jun 03 '11 at 13:03
  • If you are asked, it is likely for some test or job interview. Isn't it ? If so, what have you done so far and where are you stuck ? – ereOn Jun 03 '11 at 13:04
  • 1
    Surely this makes no sense. It alls depends how long the line is. Both C++ and Java make it easy to put everything on one line for the most part. – MGwynne Jun 03 '11 at 13:04
  • 3
    Vote to close for "plz to be sending codes" – John Dibling Jun 03 '11 at 13:05
  • @ John: no its not. Its a question asked in interview to me. @Joe : I can find reverse and then check with other. But how come in one line in C++? I have no idea – Stuti Jun 03 '11 at 13:06
  • I think we cannot do it in one line using c++ .. I am not aware of java. – Vamsi Krishna B Jun 03 '11 at 13:08
  • 2
    http://codegolf.stackexchange.com – Kevin Jun 03 '11 at 13:09
  • 1
    @Krishna @Stuti in C++ it's just `str == std::string(str.rbegin(), str.rend())` or `equal(str.begin(), str.end(), str.rbegin())` – Cubbi Jun 03 '11 at 13:34
  • 1
    nice solution @Cubbi. Since this question explicitly asks for a one-liner I don't agree with that it's a dup... – aioobe Jun 03 '11 at 13:35
  • @Cubbi: the second is the correct approach. No need to create a reversed copy of the string. To make it even more efficient, you can do: `std::equal( str.begin(), str.begin() + str.size()/2, str.rbegin() )` to reduce the time in half. Single line, linear complexity, no more than one comparison performed on each individual character... what else can you hope for? – David Rodríguez - dribeas Jun 03 '11 at 13:40
  • @aioobe @Cubbi: very thnx to you both – Stuti Jun 04 '11 at 10:43

2 Answers2

26

In Java, String does not have a reverse method. StringBuilder has though, so you can still do it in one line:

boolean palindrome = str.contentEquals(new StringBuilder(str).reverse());

Ideone.com demo

aioobe
  • 413,195
  • 112
  • 811
  • 826
2

Reverse the string using reverse and then compare with original string.

String str="ABBA"
if(str.COmpareTo(str.reverse()) ==0)
//String is palindrome.
Algorithmist
  • 6,657
  • 7
  • 35
  • 49