Wednesday, January 5, 2022

Java String Reverse (2 pointer type problem)

 A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward.


Given a string , print Yes if it is a palindrome, print No otherwise.

Constraints

  •  will consist at most  lower case english letters.

Sample Input

madam

Sample Output

Yes
Answer:
Approach1:
import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        
        Scanner sc=new Scanner(System.in);
        String A=sc.next();
        int k =0;
        /* Enter your code here. Print output to STDOUT. */
//Sliding window
         for(int i=0,j=A.length()-1;i<=j;i++,j--) {

            if(A.charAt(i)!=A.charAt(j)) 
            {
                k=1;
                break;
            }

            }

    System.out.println((k==0)?"Yes":"No");
        
    }
}



Approach2:
System.out.println( A.equals( new StringBuilder(A).reverse().toString()) 
    ? "Yes" : "No" );

No comments:

Post a Comment

Java Regex

You are updating the username policy on your company's internal networking platform. According to the policy, a username is considered v...