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.
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
Method 1: Traditional Loop
Method 2: Using Regular Expressions
Method 3: Using Apache Commons Lang
Last updated