Mark As Completed Discussion

In many programming interviews, you may come across problems that involve working with strings. String problems can range from checking if a string is a palindrome to manipulating strings to perform specific tasks.

Let's start by exploring one common string problem - checking if a string is a palindrome.

A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward. For example, "level" and "radar" are palindromes.

To solve this problem, we can use the two-pointer technique. We initialize two pointers, one at the beginning of the string and the other at the end. We compare the characters at these pointers and move them towards the center of the string until they meet.

Here's a Java program that checks if a given string is a palindrome:

TEXT/X-JAVA
1public class PalindromeChecker {
2
3    public static boolean isPalindrome(String str) {
4        int len = str.length();
5        for (int i = 0; i < len / 2; i++) {
6            if (str.charAt(i) != str.charAt(len - 1 - i)) {
7                return false;
8            }
9        }
10        return true;
11    }
12
13    public static void main(String[] args) {
14        String word1 = "level";
15        String word2 = "algorithm";
16        System.out.println(word1 + " is palindrome: " + isPalindrome(word1));
17        System.out.println(word2 + " is palindrome: " + isPalindrome(word2));
18    }
19}

In this program, we define a method isPalindrome that takes a string str as input and checks if it is a palindrome. The method uses a for loop and the two-pointer technique to compare characters from the beginning and end of the string. If any pair of characters is not the same, the method returns false. If all pairs of characters are the same, the method returns true.

We can test the isPalindrome method with different strings, such as "level" and "algorithm", and check if they are palindromes.

Try running the program and observe the output to see if the correct palindromes are identified.

JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment