String DSA Questions and Answers in Java
1. Reverse a String
public class ReverseString {
public static void main(String[] args) {
String input = "Hello World";
char[] chars = input.toCharArray();
String reversed = "";
for (int i = chars.length - 1; i >= 0; i--) {
reversed += chars[i];
}
System.out.println("Reversed String: " + reversed);
}
}
2. Check if a String is a Palindrome
public class PalindromeCheck {
public static void main(String[] args) {
String str = "madam";
boolean isPalindrome = true;
for (int i = 0, j = str.length() - 1; i < j; i++, j--) {
if (str.charAt(i) != str.charAt(j)) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
System.out.println("The string is a palindrome.");
} else {
System.out.println("The string is not a palindrome.");
}
}
}
3. Count the Number of Vowels and Consonants
public class VowelConsonantCount {
public static void main(String[] args) {
String str = "Hello World";
str = str.toLowerCase();
int vowels = 0, consonants = 0;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c >= 'a' && c <= 'z') {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowels++;
} else {
consonants++;
}
}
}
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
}
}
4. Check if Two Strings are Anagrams
public class AnagramCheck {
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
if (areAnagrams(str1, str2)) {
System.out.println("The strings are anagrams.");
} else {
System.out.println("The strings are not anagrams.");
}
}
public static boolean areAnagrams(String str1, String str2) {
if (str1.length() != str2.length()) return false;
int[] freq = new int[26];
for (int i = 0; i < str1.length(); i++) {
freq[str1.charAt(i) - 'a']++;
freq[str2.charAt(i) - 'a']--;
}
for (int count : freq) {
if (count != 0) return false;
}
return true;
}
}
5. Find the First Non-Repeating Character
public class FirstNonRepeatingChar {
public static void main(String[] args) {
String str = "swiss";
char result = findFirstNonRepeatingChar(str);
if (result != '') {
System.out.println("First non-repeating character: " + result);
} else {
System.out.println("No non-repeating character found.");
}
}
public static char findFirstNonRepeatingChar(String str) {
int[] freq = new int[256];
for (int i = 0; i < str.length(); i++) {
freq[str.charAt(i)]++;
}
for (int i = 0; i < str.length(); i++) {
if (freq[str.charAt(i)] == 1) {
return str.charAt(i);
}
}
return '';
}
}
6. Find the Longest Palindromic Substring
public class LongestPalindromicSubstring {
public static void main(String[] args) {
String str = "babad";
System.out.println("Longest Palindromic Substring: " + longestPalindrome(str));
}
public static String longestPalindrome(String s) {
int n = s.length();
int maxLength = 0;
String longest = "";
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
if (isPalindrome(s, i, j)) {
int len = j - i + 1;
if (len > maxLength) {
maxLength = len;
longest = s.substring(i, j + 1);
}
}
}
}
return longest;
}
public static boolean isPalindrome(String s, int start, int end) {
while (start < end) {
if (s.charAt(start) != s.charAt(end)) {
return false;
}
start++;
end--;
}
return true;
}
}
7. Remove Duplicates from a String
public class RemoveDuplicates {
public static void main(String[] args) {
String str = "programming";
System.out.println("String after removing duplicates: " +
removeDuplicates(str));
}
public static String removeDuplicates(String str) {
boolean[] seen = new boolean[256];
String result = "";
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (!seen[c]) {
seen[c] = true;
result += c;
}
}
return result;
}
}
8. Find the Frequency of Characters in a String
public class CharacterFrequency {
public static void main(String[] args) {
String str = "apple";
int[] freq = new int[256];
for (int i = 0; i < str.length(); i++) {
freq[str.charAt(i)]++;
}
System.out.println("Character Frequencies:");
for (int i = 0; i < 256; i++) {
if (freq[i] > 0) {
System.out.println((char) i + ": " + freq[i]);
}
}
}
}
9. Find the Longest Common Prefix
public class LongestCommonPrefix {
public static void main(String[] args) {
String[] strs = {"flower", "flow", "flight"};
System.out.println("Longest Common Prefix: " + longestCommonPrefix(strs));
}
public static String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) return "";
String prefix = strs[0];
for (int i = 1; i < strs.length; i++) {
prefix = findCommonPrefix(prefix, strs[i]);
if (prefix.isEmpty()) break;
}
return prefix;
}
public static String findCommonPrefix(String str1, String str2) {
String result = "";
int len = Math.min(str1.length(), str2.length());
for (int i = 0; i < len; i++) {
if (str1.charAt(i) == str2.charAt(i)) {
result += str1.charAt(i);
} else {
break;
}
}
return result;
}
}
10. Check if a String Contains Only Digits
public class OnlyDigitsCheck {
public static void main(String[] args) {
String str = "12345";
System.out.println("Contains only digits: " + containsOnlyDigits(str));
}
public static boolean containsOnlyDigits(String str) {
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) < '0' || str.charAt(i) > '9') {
return false;
}
}
return true;
}
}
11. Remove All White Spaces from a String
public class RemoveSpaces {
public static void main(String[] args) {
String str = "Hello World!";
System.out.println("String without spaces: " + removeSpaces(str));
}
public static String removeSpaces(String str) {
String result = "";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) != ' ') {
result += str.charAt(i);
}
}
return result;
}
}
12. Convert a String to Lowercase Without Using toLowerCase
public class ToLowerCase {
public static void main(String[] args) {
String str = "HeLLo WoRLd!";
System.out.println("Lowercase: " + toLowerCase(str));
}
public static String toLowerCase(String str) {
String result = "";
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c >= 'A' && c <= 'Z') {
result += (char) (c + 32);
} else {
result += c;
}
}
return result;
}
}
13. Find All Substrings of a String
public class Substrings {
public static void main(String[] args) {
String str = "abc";
generateSubstrings(str);
}
public static void generateSubstrings(String str) {
for (int i = 0; i < str.length(); i++) {
for (int j = i; j < str.length(); j++) {
for (int k = i; k <= j; k++) {
System.out.print(str.charAt(k));
}
System.out.println();
}
}
}
}