Saturday, August 24, 2019

Can you write an algorithm to check palindrome?

Problem statement:
Given a string. Can you check whether it is a palindrome or not?
  1. public class Palindrome {
  2. public static void main(String[] args) {
  3. String s = "abcba";
  4. char c[] = s.toCharArray();
  5. int p = c.length - 1;
  6. for (int i = 0; i < c.length / 2; i++) {
  7. if (c[i] == c[p]) {
  8. p--;
  9. } else {
  10. System.out.println("Not palindrome");
  11. return;
  12. }
  13. }
  14. System.out.println("Palindrome");
  15. }
  16. }
Output:
Palindrome
Time complexity: O(n/2)

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...