HackerRank Java String Reverse Problem Solution
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
Solution 1:
import java.io.*;import java.util.*;
public class Solution {
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String s = scanner.next(); String reverse = new StringBuilder(s).reverse().toString(); if(s.equals(reverse)) { System.out.println("Yes"); } else{ System.out.println("No"); } /* Enter your code here. Print output to STDOUT. */ }}
Solution 2:
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(); /* Enter your code here. Print output to STDOUT. */ boolean palindrome = true; for(int i = 0; i<A.length()/2;i++) { if(!A.substring(i,i+1).equals(A.substring(A.length()-i-1,A.length()-i))) { palindrome = false; } } if(palindrome){System.out.println("Yes");} else{System.out.println("No");} }}
Solution 3:
import java.util.Scanner;
public class Solution { public static void main(String[] args) { /* Read input */ Scanner scan = new Scanner(System.in); String str = scan.nextLine(); scan.close(); /* Reverse string and compare to original */ /* If a String is equivalent to itself when reversed, it's a palindrome */ String reversed = new StringBuilder(str).reverse().toString(); System.out.println(str.equals(reversed) ? "Yes" : "No"); }}
Solution 4:
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();,
String rev = "";
for(int i=A.length()-1;i>=0;i--)
rev+=A.charAt(i);
if(rev.equals(A))
System.out.println("Yes");
else
System.out.println("No");
}
}
टिप्पणियाँ
एक टिप्पणी भेजें