Reading history

Java String Coding Problems

7 min read 0 views

Solve classic Java string problems: palindromes, anagrams, reversing words, first unique character, compression, word frequency and title case.

String puzzles appear in almost every programming test, from university lab exams to job interviews. The good news is that most of them use the same few ideas: two indexes moving towards each other, a count of each character, or a map of word frequencies. This lesson solves eight classic problems in Java. Each solution is short, tested, and explained step by step, so you can reuse the ideas in new problems.

In this lesson you will learn

  • Palindrome check that ignores case and punctuation
  • Anagram check with a count array
  • Reversing words and characters
  • First non-repeating character with LinkedHashMap
  • Run-length compression, word frequency and title case

You should know Java strings, StringBuilder and HashMap.

Palindromes, Anagrams and Reversing

import java.util.*;

public class Main {
    static boolean isPalindrome(String s) {
        String t = s.toLowerCase().replaceAll("[^a-z0-9]", "");   // keep letters and digits
        int i = 0, j = t.length() - 1;
        while (i < j) {
            if (t.charAt(i++) != t.charAt(j--)) return false;
        }
        return true;
    }

    static boolean isAnagram(String a, String b) {
        int[] count = new int[26];
        for (char c : a.toLowerCase().toCharArray()) if (Character.isLetter(c)) count[c - 'a']++;
        for (char c : b.toLowerCase().toCharArray()) if (Character.isLetter(c)) count[c - 'a']--;
        for (int n : count) if (n != 0) return false;
        return true;
    }

    static String reverseWords(String s) {
        List<String> words = Arrays.asList(s.trim().split("\\s+"));
        Collections.reverse(words);
        return String.join(" ", words);
    }

    static int countVowels(String s) {
        int n = 0;
        for (char c : s.toLowerCase().toCharArray()) if ("aeiou".indexOf(c) >= 0) n++;
        return n;
    }

    public static void main(String[] args) {
        for (String s : new String[]{"Madam", "A man, a plan, a canal: Panama", "Java"})
            System.out.println("isPalindrome(\"" + s + "\") = " + isPalindrome(s));

        System.out.println("isAnagram(listen, silent)   = " + isAnagram("listen", "silent"));
        System.out.println("isAnagram(Dormitory, dirty room) = " + isAnagram("Dormitory", "dirty room"));
        System.out.println("isAnagram(apple, paddle)    = " + isAnagram("apple", "paddle"));

        System.out.println("reverseWords = " + reverseWords("  I love   learning Java  "));
        System.out.println("reverse chars = " + new StringBuilder("Bangladesh").reverse());
        System.out.println("countVowels(Programming) = " + countVowels("Programming"));
    }
}

Output

isPalindrome("Madam") = true
isPalindrome("A man, a plan, a canal: Panama") = true
isPalindrome("Java") = false
isAnagram(listen, silent)   = true
isAnagram(Dormitory, dirty room) = true
isAnagram(apple, paddle)    = false
reverseWords = Java learning love I
reverse chars = hsedalgnaB
countVowels(Programming) = 3
  • Palindrome. First we clean the text: lower case, and replaceAll("[^a-z0-9]", "") removes everything except letters and digits. Then i starts at the front and j at the back. If any pair differs, it is not a palindrome. This needs no extra string and stops early.
  • Anagram. Two words are anagrams if they use the same letters the same number of times. The array count has one slot per letter. We add 1 for each letter of the first word and subtract 1 for the second. If every slot ends at 0, the counts matched. This is O(n), faster than sorting both words.
  • Reverse words. trim() removes outside spaces and split("\\s+") splits on one or more spaces, so extra spaces vanish. Collections.reverse flips the list and String.join glues it back.
  • Reverse characters. new StringBuilder(s).reverse() does it in one line.
  • Count vowels. "aeiou".indexOf(c) >= 0 is a short way to ask whether c is one of those letters.

Problems That Use Counting

import java.util.*;

public class Main {
    static Character firstUnique(String s) {
        Map<Character, Integer> freq = new LinkedHashMap<>();   // keeps first-seen order
        for (char c : s.toCharArray()) freq.merge(c, 1, Integer::sum);
        for (var e : freq.entrySet()) if (e.getValue() == 1) return e.getKey();
        return null;
    }

    static String compress(String s) {                // "aaabcc" -> "a3b1c2"
        StringBuilder out = new StringBuilder();
        int i = 0;
        while (i < s.length()) {
            char c = s.charAt(i);
            int j = i;
            while (j < s.length() && s.charAt(j) == c) j++;
            out.append(c).append(j - i);
            i = j;
        }
        return out.length() < s.length() ? out.toString() : s;   // only if shorter
    }

    static Map<String, Integer> wordFrequency(String text) {
        Map<String, Integer> freq = new TreeMap<>();
        for (String w : text.toLowerCase().split("[^a-z]+"))
            if (!w.isEmpty()) freq.merge(w, 1, Integer::sum);
        return freq;
    }

    static String capitalise(String s) {
        StringBuilder out = new StringBuilder();
        for (String w : s.trim().split("\\s+")) {
            out.append(Character.toUpperCase(w.charAt(0)))
               .append(w.substring(1).toLowerCase()).append(' ');
        }
        return out.toString().trim();
    }

    public static void main(String[] args) {
        System.out.println("firstUnique(swiss)     = " + firstUnique("swiss"));
        System.out.println("firstUnique(aabb)      = " + firstUnique("aabb"));
        System.out.println("compress(aaabccccd)    = " + compress("aaabccccd"));
        System.out.println("compress(abc)          = " + compress("abc"));
        System.out.println("capitalise             = " + capitalise("  dHAKA   uNIVERSITY "));
        System.out.println("wordFrequency          = "
            + wordFrequency("The rain fell. The river rose, and the rain did not stop."));
    }
}

Output

firstUnique(swiss)     = w
firstUnique(aabb)      = null
compress(aaabccccd)    = a3b1c4d1
compress(abc)          = abc
capitalise             = Dhaka University
wordFrequency          = {and=1, did=1, fell=1, not=1, rain=2, river=1, rose=1, stop=1, the=3}
  • First unique character. merge(c, 1, Integer::sum) adds 1 to a character’s count, starting from 1 the first time. A LinkedHashMap remembers the order keys were first added, so the first entry with count 1 is the answer. In “swiss”, s appears three times, and w is the first letter that appears only once.
  • Compression. The inner while loop moves j to the end of a run of equal characters. The run length is j - i. We return the compressed form only if it is actually shorter, so “abc” stays “abc”.
  • Title case. Each word gets an upper-case first letter and a lower-case rest. Splitting on \\s+ also tidies the double spaces.
  • Word frequency. split("[^a-z]+") breaks the text at anything that is not a letter, so full stops and commas disappear. A TreeMap keeps the words in alphabetical order.
IdeaUse it forTime
Two indexes from both endsPalindromes, reversing in placeO(n)
Count array of 26Anagrams, letter counts (English only)O(n)
HashMap / LinkedHashMap countsAny characters or words, first uniqueO(n)
Scan runs with an inner loopCompression, longest runO(n)

Common Mistakes

  1. Building a string with += inside a loop. Each step makes a new string. Use StringBuilder.
  2. Comparing strings with ==. Use equals, or equalsIgnoreCase.
  3. Splitting on a single space. split(" ") creates empty words when there are double spaces; use split("\\s+") after trim().
  4. Forgetting case. “Madam” is a palindrome only if you compare in one case.
  5. Using a 26-slot array for text that may contain other characters. c - 'a' goes out of range; use a map or check isLetter first.

Practice Exercises

Exercise 1. Write isPangram(String s), which is true if the text uses every letter from a to z at least once.

Show answer
static boolean isPangram(String s) {
    boolean[] seen = new boolean[26];
    for (char c : s.toLowerCase().toCharArray())
        if (c >= 'a' && c <= 'z') seen[c - 'a'] = true;
    for (boolean b : seen) if (!b) return false;
    return true;
}
// isPangram("The quick brown fox jumps over the lazy dog") is true

Exercise 2. Find the most common character in "programming". If two tie, return the one that appears first.

Show answer
Map<Character, Integer> f = new LinkedHashMap<>();
for (char c : "programming".toCharArray()) f.merge(c, 1, Integer::sum);
char best = ' ';
int most = 0;
for (var e : f.entrySet())
    if (e.getValue() > most) { most = e.getValue(); best = e.getKey(); }
System.out.println(best + " " + most);   // r 2

r, g and m each appear twice. Using > instead of >= keeps the first one found, which is r.

Frequently Asked Questions

What is the fastest way to check if two strings are anagrams in Java?

Count the letters. Use an int array of 26 for English letters, add one for each letter of the first string and subtract one for the second, then check that every count is zero. This runs in O(n) time, while sorting both strings takes O(n log n).

How do I reverse a string in Java?

The simplest way is new StringBuilder(s).reverse().toString(). To reverse the order of words instead, split on whitespace, reverse the list with Collections.reverse, and join it with String.join.

Summary

  • Two indexes moving inwards solve palindromes without extra memory.
  • Count letters for anagrams and pangrams; use maps for any characters or words.
  • LinkedHashMap keeps first-seen order, which solves “first unique” problems.
  • Clean input first: toLowerCase, trim, split("\\s+"), replaceAll.
  • Build output with StringBuilder.

Next: Java Two Pointers and Sliding Window.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *