Write program to palindrome string
//Method 1
public void PalindromeString{
//main method
public static void main(String args[])
{
//String declare and initiation
String s="MADAM";
String rev="";
for(int i=s,lenght()-1;i>=0;i--){
rev=rev+s.charAt(i);
}
if(s.equals(rev)){
System.out.println("this is palindrome string");//MADAM
}
else{
System.out.println("This is not palindrome screen"); //!=MADAM
}
}
}
=====================================================
🔹 Step 1: Start with the Concept
A palindrome string is a string that reads the same forward and backward (e.g., "MADAM", "LEVEL").
The logic is to reverse the string and compare it with the original.
🔹 Step 2: Walk Through the Code
String Declaration:
javaString s = "MADAM";→ This is the input string we want to check.
Reverse Logic:
javaString rev = ""; for(int i = s.length() - 1; i >= 0; i--) { rev = rev + s.charAt(i); }→ Loop starts from the last character and appends each character to
rev. → At the end,revcontains the reversed string.Comparison:
javaif(s.equals(rev)) { System.out.println("This is palindrome string"); } else { System.out.println("This is not palindrome string"); }→ If original string equals reversed string, it’s a palindrome.
🔹 Step 3: Correct Mistakes in Code (Interviewers notice this!)
lenght()should be corrected tolength().Method declaration should be:
javapublic class PalindromeString { public static void main(String[] args) { //code } }
🔹 Step 4: Explain in Interview Style
Here’s a sample answer you can give:
“To check if a string is a palindrome, I reverse the string using a loop and compare it with the original. If both are equal, the string is a palindrome. For example, with i/p=
MADAM, the o/p=MADAM, so the program prints that it is a palindrome. I usedcharAt()to fetch characters andequals()for comparison. Also, I ensured to uselength()correctly to avoid compilation errors.”
-----------------------------------------------------------------------
//Method 2
//optimise code
You can mention optimization: Instead of reversing the whole string, compare characters from start and end moving inward (reduces time and memory).
for(int i=0; i<s.length()/2; i++) {
if(s.charAt(i) != s.charAt(s.length()-1-i)) {
return false;
}
}
return true;
Comments
Post a Comment