Tuesday, April 17, 2018

How to check palindrome ?

// Method - I:
  1. public class PalindromAlgoritham {

  2. public static void main(String[] args) {
  3. String s1 = "ABCBA";
  4. int p = s1.length() - 1;
  5. boolean flag = true;
  6. for (int i = 0; i < s1.length()/2; i++) {
  7. if (s1.charAt(i) != s1.charAt(p)) {
  8. flag=false;
  9. break;
  10. }
  11. p--;
  12. }
  13. System.out.println((flag?"Palindrome":"Not Palindrome"));
  14. }

  15. }
Output: Palindrome
Time complexity: O(n/2)

// Method - II:
  1. public class PalindromeByCharAtAlgorithm {

  2. public static void main(String[] args) {
  3. String s1 = "ABCDCBA ABCDCBA ABCDCBA";
  4. String rev = "";
  5. for (int i = s1.length() - 1; i >= 0; i--) {
  6. rev = rev + s1.charAt(i);
  7. }
  8. if (s1.equals(rev)) {
  9. System.out.println("Palindrome !!");
  10. } else {
  11. System.out.println("Not Palindrome !!");
  12. }

  13. }

  14. }
OutputPalindrome !!
Time Complexity: O(nlog(n))

// Method - III:
  1. public class PalindromeByStringBuilderAlgorithm {

  2. public static void main(String[] args) {

  3. String str = "313";
  4. int value = Integer.parseInt(str);

  5. StringBuilder sb = new StringBuilder(str);
  6. String reverse = sb.reverse().toString();
  7. int rvalue = Integer.parseInt(reverse);

  8. if (value == rvalue) {
  9. System.out.println("Palindrome !!");
  10. } else {
  11. System.out.println("Not palindrome !!");
  12. }
  13. }
  14. }
Output: Palindrome !!
Time Complexity: O(n)

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...