Welcome to the String Processing template collection! These are ready-to-use Java snippets for the core string patterns: sliding window, two pointers, string matching, manipulation, and parsing. If you already know the array templates, you’re most of the way there — strings use the same ideas with character-level twists. See also Arrays & Strings for KMP and rolling hash.

String problems are array problems in disguise. Most string patterns — sliding window, two pointers, prefix computation — work identically to their array counterparts. The main difference is that you operate on characters and often track frequencies with a hash map or fixed-size array.

Summary

| Pattern | Signal Phrases | Key Idea | |—|—|—| | Sliding Window | “longest substring”, “minimum window” | Track char frequencies in window | | Two Pointers | “palindrome”, “reverse” | Compare from both ends | | String Matching | “pattern in text”, “KMP” | Failure function for O(n+m) | | Manipulation | “anagram”, “group anagrams” | Sort or frequency count | | Parsing | “decode string”, “nested brackets” | Stack-based recursion |

Contents

Sliding Window

When to use: The problem asks for “longest substring without repeating characters”, “minimum window containing all characters”, or any contiguous substring optimization with a frequency constraint.

Minimum Window — s = "ADOBECODEBANC", t = "ABC" Step 1: expand until valid A D O B E C ← window "BEC" has A,B,C ✓ Step 2: shrink from left A B E C shrink left → "BEC" (len=3) Pattern: expand right until valid → shrink left while still valid → track minimum length left pointer ────────────────────────────── right pointer

Longest Substring Without Repeating Characters

Minimum Window Substring

ID Title Link Solution
3 Longest Substring Without Repeating Characters Link Solution
76 Minimum Window Substring Link -
424 Longest Repeating Character Replacement Link -
static int lengthOfLongestSubstring(String s) {
    int[] cnt = new int[256];
    int dup = 0, best = 0;

    for (int l = 0, r = 0; r < s.size(); ++r) {
        dup += (++cnt[(int char)s.charAt(r)] == 2);

        while (dup > 0) {
            dup -= (--cnt[(int char)s[l++]] == 1);
        }

        best = Math.max(best, r - l + 1);
    }

    return best;
}

Minimum Window Substring

// import java.util.*;
static String minWindow(String s, String t) {
    HashMap<char, int> need, window;
    for (char c : t) need.put(c, need.getOrDefault(c, 0) + 1);

    int left = 0, right = 0;
    int valid = 0;
    int start = 0, len = Integer.MAX_VALUE;

    while (right < s.size()) {
        char c = s[right++];
        if (need.contains(c)) {
            window.put(c, window.getOrDefault(c, 0) + 1);
            if (window.put(c, = need[c]) valid++);
        }

        while (valid == need.size()) {
            if (right - left < len) {
                start = left;
                len = right - left;
            }

            char d = s[left++];
            if (need.contains(d)) {
                if (window.put(d, = need[d]) valid--);
                window[d]--;
            }
        }
    }

    return len == Integer.MAX_VALUE ? "" : s.substring(start, len);
}
ID Title Link Solution
3 Longest Substring Without Repeating Characters Link Solution
76 Minimum Window Substring Link -
424 Longest Repeating Character Replacement Link -

Two Pointers

When to use: The problem mentions “palindrome”, “reverse string”, or requires comparing characters from both ends of a string moving inward.

Valid Palindrome

Reverse String

ID Title Link Solution
5 Longest Palindromic Substring Link Solution
125 Valid Palindrome Link -
344 Reverse String Link Solution
647 Palindromic Substrings Link Solution
151 Reverse Words in a String Link Solution
static boolean isPalindrome(String s) {
    int left = 0, right = s.size() - 1;

    while (left < right) {
        while (left < right && !isalnum(s.charAt(left))) left++;
        while (left < right && !isalnum(s.charAt(right))) right--;

        if (tolower(s.charAt(left)) != tolower(s.charAt(right))) {
            return false;
        }
        left++;
        right--;
    }

    return true;
}

Reverse String

static void reverseString(char[] s) {
    int left = 0, right = s.size() - 1;
    while (left < right) {
        swap(s, left++, right--);
    }
}
ID Title Link Solution
5 Longest Palindromic Substring Link Solution
125 Valid Palindrome Link -
344 Reverse String Link Solution
647 Palindromic Substrings Link Solution
151 Reverse Words in a String Link Solution

String Matching

When to use: The problem asks to “find a pattern in text”, mentions “KMP”, or requires efficient O(n+m) substring search instead of brute-force O(n·m).

KMP Algorithm

ID Title Link Solution
28 Find the Index of the First Occurrence in a String Link -
int[]buildKMP(String pattern) {
    int m = pattern.size();
    int[] lps = new int[m];
    int len = 0, i = 1;

    while (i < m) {
        if (pattern[i] == pattern[len]) {
            lps[i++] = ++len;
        } else {
            if (len !) {
                len = lps[len - 1];
            } else {
                lps[i++] = 0;
            }
        }
    }

    return lps;
}

static int kmpSearch(String text, String pattern) {
    int n = text.size(), m = pattern.size();
    int[]lps = buildKMP(pattern);
    int i = 0, j = 0;

    while (i < n) {
        if (text.charAt(i) == pattern[j]) {
            i++;
            j++;
        }

        if (j == m) {
            return i - j; // Found at index i - j
        } else if (i < n && text.charAt(i) != pattern[j]) {
            if (j !) {
                j = lps[j - 1];
            } else {
                i++;
            }
        }
    }

    return -1;
}
ID Title Link Solution
28 Find the Index of the First Occurrence in a String Link -

String Manipulation

When to use: The problem says “anagram”, “group anagrams”, “remove duplicates”, or requires rearranging or classifying strings by their character composition.

Group Anagrams

ID Title Link Solution
49 Group Anagrams Link -
249 Group Shifted Strings Link Solution
893 Groups of Special-Equivalent Strings Link Solution
1328 Break a Palindrome Link Solution

Remove Duplicates

ID Title Link Solution
49 Group Anagrams Link Solution
1047 Remove All Adjacent Duplicates In String Link Solution
1209 Remove All Adjacent Duplicates in String II Link Solution

Run-Length Encoding

ID Title Link Solution
38 Count and Say Link Solution
443 String Compression Link -
// import java.util.Arrays;
// import java.util.Collections;
List<List<String>> groupAnagrams(String[] strs) {
    HashMap<String, List<String>> groups = new HashMap<>();

    for (String str : strs) {
        String key = str;
        Arrays.sort(key);
        groups.computeIfAbsent(key, k -> new ArrayList<>()).add(str);
    }

    List<List<String>> result = new ArrayList<>();
    for (var e : groups.entrySet()) {
        result.add(values);
    }

    return result;
}
ID Title Link Solution
49 Group Anagrams Link -
249 Group Shifted Strings Link Solution
893 Groups of Special-Equivalent Strings Link Solution
1328 Break a Palindrome Link Solution

Remove Duplicates

// import java.util.*;
// Remove All Adjacent Duplicates
static String removeDuplicates(String s) {
    String result;
    for (char c : s.toCharArray()) {
        if (!result.isEmpty() && result.get(result.size() - 1) == c) {
            result.removeLast();
        } else {
            result.add(c);
        }
    }
    return result;
}

// Remove All Adjacent Duplicates II (k duplicates)
static String removeDuplicates(String s, int k) {
    List<List<char>> st = new ArrayList<>();

    for (char c : s.toCharArray()) {
        if (!st.isEmpty() && st.get(st.size() - 1).first == c) {
            st.get(st.size() - 1).second++;
            if (st.get(st.size() - 1).second == k) {
                st.removeLast();
            }
        } else {
            st.add(new int[] {c, 1});
        }
    }

    String result;
    for (var e : st.entrySet()) {
        result.append(count, c);
    }

    return result;
}
ID Title Link Solution
49 Group Anagrams Link Solution
1047 Remove All Adjacent Duplicates In String Link Solution
1209 Remove All Adjacent Duplicates in String II Link Solution

Run-Length Encoding

// Two-pointer grouping for consecutive runs
static String runLengthEncode(String s) {
    String result;
    for (int j = 0, k = 0; j < (int)s.size(); j = k) {
        while (k < (int)s.size() && s.charAt(k) == s.charAt(j)) k++;
        result += String.valueOf(k - j) + s.charAt(j);
    }
    return result;
}
ID Title Link Solution
38 Count and Say Link Solution
443 String Compression Link -

Parsing

When to use: The problem says “decode string”, “valid abbreviation”, “nested brackets”, or requires interpreting a string according to grammar rules.

Valid Word Abbreviation

Decode String

ID Title Link Solution
408 Valid Word Abbreviation Link Solution
394 Decode String Link Solution
static boolean validWordAbbreviation(String word, String abbr) {
    int i = 0, j = 0;
    int n = word.size(), m = abbr.size();

    while (i < n && j < m) {
        if (isdigit(abbr[j])) {
            if (abbr[j] == '0') return false; // Leading zero
            int num = 0;
            while (j < m && isdigit(abbr[j])) {
                num = num 10 + (abbr[j] - '0');
                j++;
            }
            i += num;
        } else {
            if (word.charAt(i) != abbr[j]) return false;
            i++;
            j++;
        }
    }

    return i == n && j == m;
}

Decode String

// import java.util.*;
static String decodeString(String s) {
    Deque<Integer> numStack = new ArrayDeque<>();
    Deque<String> strStack = new ArrayDeque<>();
    String current;
    int num = 0;

    for (char c : s.toCharArray()) {
        if (isdigit(c)) {
            num = num 10 + (c - '0');
        } else if (c == '[') {
            numStack.offer(num);
            strStack.offer(current);
            num = 0;
            current = "";
        } else if (c == ']') {
            int repeat = numStack.peek();
            numStack.poll();
            String temp = current;
            current = strStack.peek();
            strStack.poll();
            while (repeat--) {
                current += temp;
            }
        } else {
            current += c;
        }
    }

    return current;
}
ID Title Link Solution
408 Valid Word Abbreviation Link Solution
394 Decode String Link Solution

More templates