π― 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:
- One starts at the beginning
- One starts at the end
- 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β:
- Center at C β just βCβ
- Center at B β just βBβ
- Center between B-B β βBBβ β¨ (longest!)
- 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