// Method - I:
Time complexity: O(n/2)
- public class PalindromAlgoritham {
- public static void main(String[] args) {
- String s1 = "ABCBA";
- int p = s1.length() - 1;
- boolean flag = true;
- for (int i = 0; i < s1.length()/2; i++) {
- if (s1.charAt(i) != s1.charAt(p)) {
- flag=false;
- break;
- }
- p--;
- }
- System.out.println((flag?"Palindrome":"Not Palindrome"));
- }
- }
Time complexity: O(n/2)
// Method - II:
- public class PalindromeByCharAtAlgorithm {
- public static void main(String[] args) {
- String s1 = "ABCDCBA ABCDCBA ABCDCBA";
- String rev = "";
- for (int i = s1.length() - 1; i >= 0; i--) {
- rev = rev + s1.charAt(i);
- }
- if (s1.equals(rev)) {
- System.out.println("Palindrome !!");
- } else {
- System.out.println("Not Palindrome !!");
- }
- }
- }
Output: Palindrome !!
Time Complexity: O(nlog(n))
Time Complexity: O(nlog(n))
// Method - III:
- public class PalindromeByStringBuilderAlgorithm {
- public static void main(String[] args) {
- String str = "313";
- int value = Integer.parseInt(str);
- StringBuilder sb = new StringBuilder(str);
- String reverse = sb.reverse().toString();
- int rvalue = Integer.parseInt(reverse);
- if (value == rvalue) {
- System.out.println("Palindrome !!");
- } else {
- System.out.println("Not palindrome !!");
- }
- }
- }
Output: Palindrome !!
Time Complexity: O(n)
Time Complexity: O(n)
No comments:
Post a Comment