String Patterns

Loading concept...

🎯 String Patterns: The Magic of Text Detective Work

Imagine you’re a detective with a magnifying glass, looking for secret messages hidden in text. That’s what string patterns are all about!


🏠 Our Story: The Word Detective Agency

Meet Sam the String Detective! Sam works at a special agency where they solve text mysteries. Every day, people bring Sam puzzles like:

  • β€œIs this word the same backwards?”
  • β€œCan we squish this long text into something smaller?”
  • β€œAre these two words secretly the same letters scrambled?”

Let’s join Sam and learn the secrets of string pattern detection!


πŸ“š Part 1: Strings Fundamentals

What is a String?

Think of a string like a necklace of letter beads. Each bead is one character, and they’re all connected in order.

String name = "HELLO";
// H-E-L-L-O are 5 beads
// on one necklace

Key Things About Strings

Property What It Means Example
Length How many beads "CAT".length() = 3
Index Bead position (starts at 0!) "CAT".charAt(0) = β€˜C’
Immutable Can’t change beads Must make new string

The Index Secret 🀫

Here’s a tricky thing! Counting starts at 0, not 1.

graph TD A["String: HELLO"] --> B["H = index 0"] B --> C["E = index 1"] C --> D["L = index 2"] D --> E["L = index 3"] E --> F["O = index 4"]

Real Example:

String word = "PIZZA";
char first = word.charAt(0);
// first = 'P'
char last = word.charAt(4);
// last = 'A'

βœ‚οΈ Part 2: String Manipulation

What is String Manipulation?

It’s like playing with clay letters. You can:

  • Cut them apart
  • Stick them together
  • Change their shape

The 5 Super Powers

πŸ”— Power 1: Joining Strings (Concatenation)

String first = "SUPER";
String second = "HERO";
String together = first + second;
// together = "SUPERHERO"

βœ‚οΈ Power 2: Cutting Strings (Substring)

String word = "BUTTERFLY";
String piece = word.substring(0, 6);
// piece = "BUTTER"
// Cut from 0 to 5 (6 not included!)

πŸ”„ Power 3: Changing Case

String shout = "hello".toUpperCase();
// shout = "HELLO"
String whisper = "HELLO".toLowerCase();
// whisper = "hello"

πŸ” Power 4: Finding Characters

String word = "BANANA";
int pos = word.indexOf('N');
// pos = 2 (first N found!)

πŸ” Power 5: Replacing Characters

String old = "cat";
String newer = old.replace('c', 'b');
// newer = "bat"

πŸ“¦ Part 3: String Compression

The Squishing Game

Imagine you have: AAABBBCCCC

Instead of writing all letters, you write:

  • A3B3C4 (letter + count)

You just made it smaller! πŸŽ‰

How Compression Works

graph TD A["AAABBBCCCC"] --> B["Count each group"] B --> C["A appears 3 times"] B --> D["B appears 3 times"] B --> E["C appears 4 times"] C --> F["Result: A3B3C4"] D --> F E --> F

The Compression Code

String compress(String s) {
    StringBuilder result =
        new StringBuilder();
    int count = 1;

    for(int i = 1; i <= s.length(); i++) {
        if(i < s.length() &&
           s.charAt(i) == s.charAt(i-1)) {
            count++;
        } else {
            result.append(s.charAt(i-1));
            result.append(count);
            count = 1;
        }
    }
    return result.toString();
}

When Compression Helps

Original Compressed Saved?
AAAA A4 βœ… Yes!
ABC A1B1C1 ❌ Longer!
AABBCC A2B2C2 Same

Rule: Only use compression if it makes things shorter!


πŸ”€ Part 4: Anagram Detection

What’s an Anagram?

Two words are anagrams if they use the exact same letters, just scrambled.

Examples:

  • LISTEN ↔ SILENT βœ…
  • CAT ↔ ACT βœ…
  • DOG ↔ CAT ❌ (different letters!)

How Sam Checks for Anagrams

graph TD A["Word 1: LISTEN"] --> B["Sort letters: EILNST"] C["Word 2: SILENT"] --> D["Sort letters: EILNST"] B --> E{"Same?"} D --> E E -->|Yes| F["ANAGRAM! βœ…"] E -->|No| G["NOT Anagram ❌"]

The Letter Counting Method

Instead of sorting, count each letter!

boolean isAnagram(String a, String b) {
    if(a.length() != b.length())
        return false;

    int[] count = new int[26];

    for(char c : a.toCharArray())
        count[c - 'a']++;

    for(char c : b.toCharArray())
        count[c - 'a']--;

    for(int n : count)
        if(n != 0) return false;

    return true;
}

Simple Example

Letter LISTEN SILENT Match?
E 1 1 βœ…
I 1 1 βœ…
L 1 1 βœ…
N 1 1 βœ…
S 1 1 βœ…
T 1 1 βœ…

All match = Anagram!


πŸͺž Part 5: Palindrome Detection

What’s a Palindrome?

A word that reads the same forwards and backwards!

Examples:

  • MOM β†’ MOM βœ…
  • RACECAR β†’ RACECAR βœ…
  • HELLO β†’ OLLEH ❌

The Mirror Test

graph TD A["RACECAR"] --> B["Front: R"] A --> C["Back: R"] B --> D{"Match?"} C --> D D -->|Yes| E["Check next pair"] E --> F["Front: A, Back: A βœ…"] F --> G["Front: C, Back: C βœ…"] G --> H["Middle: E βœ…"] H --> I["PALINDROME! πŸŽ‰"]

Simple Palindrome Check

boolean isPalindrome(String s) {
    int left = 0;
    int right = s.length() - 1;

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

Two Pointer Magic ✨

We use two fingers:

  1. One starts at the beginning
  2. One starts at the end
  3. They walk toward each other, checking matches

πŸ† Part 6: Longest Palindromic Substring

The Big Challenge

Finding the longest palindrome hidden inside a string!

Example: In β€œBABAD”

  • β€œBAB” is a palindrome (length 3)
  • β€œABA” is a palindrome (length 3)
  • Either one is the answer!

The Expand-From-Center Trick

Imagine standing at each letter and growing outward like ripples in water.

graph TD A["String: BABAD"] --> B["Try center at B"] A --> C["Try center at A"] A --> D["Try center at B"] A --> E["Try center at A"] A --> F["Try center at D"] C --> G["Expand: A β†’ BAB β†’ βœ…"] G --> H["Longest = BAB"]

Two Types of Centers

Type Example Centers
Odd length β€œABA” The middle A
Even length β€œABBA” Between B and B

The Code

String longestPalindrome(String s) {
    String longest = "";

    for(int i = 0; i < s.length(); i++) {
        // Odd length
        String odd = expand(s, i, i);
        // Even length
        String even = expand(s, i, i+1);

        if(odd.length() > longest.length())
            longest = odd;
        if(even.length() > longest.length())
            longest = even;
    }
    return longest;
}

String expand(String s, int L, int R) {
    while(L >= 0 && R < s.length()
          && s.charAt(L) == s.charAt(R)) {
        L--;
        R++;
    }
    return s.substring(L+1, R);
}

Visual Example

For β€œCBBD”:

  1. Center at C β†’ just β€œC”
  2. Center at B β†’ just β€œB”
  3. Center between B-B β†’ β€œBB” ✨ (longest!)
  4. Center at D β†’ just β€œD”

Answer: β€œBB”


πŸŽ‰ Congratulations, Detective!

You’ve learned all the string pattern secrets:

Skill What You Can Do
Fundamentals Access any character by index
Manipulation Cut, join, transform text
Compression Make repeated text smaller
Anagrams Spot scrambled twins
Palindromes Find mirror words
Longest Palindrome Find the biggest hidden mirror

Now you’re ready to solve any text mystery! πŸ”


β€œEvery string holds a pattern. You just need to know how to look.” β€” Sam the String Detective

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.