Set 3 - Strings

1. Check whether a string is a Palindrome

A string is said to be a palindrome if it is the same if we start reading it from left to right or right to left.

Example

Input: str = “abccba” Output: Yes

Input: str = “someString” Output: No

Method 1: Using naive method of String reversal

By reversing the given string and comparing, we can check if the given string is a palindrome or not.

public static boolean method1(String input) {
        String reverse = "";
        for (int i=input.length() - 1; i>=0; i--) {
            reverse = reverse.concat(String.valueOf(input.charAt(i)));
        }

        return input.equals(reverse);
    }
// Time Complexity - O(N)
// Space Complexity - O(n) where n is the length of the input string. This is because the reverse string is created and stored in a separate string variable, which takes up space in memory proportional to the length of the input string.

Method 2: Using StringBuilders

By reversing the given string using string builders, we can check if the given string is a palindrome or not.

Method 3: Using iteration over the string

Method 4: Using recursion

2. Check whether two strings are anagram

An anagram of a string is another string that contains the same characters, only the order of characters can be different.

Method 1: Using Sort

Method 2: Count characters using 2 arrays

Method 3: Count characters using 1 array

Method 4: Using HashMap

Program to reverse a String

Method 1: Using StringBuilder

Method 2: Using iteration

Method 3: Using Byte Array

Method 4: Using Arraylist and Streams

Method 5: Using StringBuffer

Method 6: Using Stacks

4. Remove Leading Zeros From String

Input : 0000012345 Output: 12345

Input: 000012345090 Output: 12345090

5. Find 1st and last digit in a String

Input : eightkpfngjsx97twozmbdtxhh Output: 9 and 7

The '\0' character is the null character in Java and many other programming languages. It is represented by the Unicode value 0. In Java, it is often used as a sentinel value or placeholder for characters.

In the provided code snippets, '\0' is used as an initial value for firstDigit and lastDigit to indicate that they have not been set to any valid digit yet. Later in the code, if a digit is found, the corresponding variable is updated with the actual digit value.

For example, if no digits are found in the input string, firstDigit and lastDigit will remain '\0', and the program can use that information to print a message indicating that no digits were found.

Method 1: Traditional Loop

Method 2: Using Regular Expressions

Method 3: Using Apache Commons Lang

Last updated