Skip to content

Commit 394921a

Browse files
committed
Added new strings problems
1 parent f8b8ee1 commit 394921a

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

02-strings/02_AnagramCheck.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Problem: Anagram Check
2+
// Author: Ataubl (codeByunique)
3+
4+
import java.util.Arrays;
5+
6+
class AnagramCheck {
7+
public static void main(String[] args) {
8+
String str1 = "listen";
9+
String str2 = "silent";
10+
11+
if (areAnagrams(str1, str2)) {
12+
System.out.println(str1 + " and " + str2 + " are anagrams.");
13+
} else {
14+
System.out.println(str1 + " and " + str2 + " are not anagrams.");
15+
}
16+
}
17+
18+
public static boolean areAnagrams(String s1, String s2) {
19+
// Step 1: Remove whitespace & convert to lowercase
20+
s1 = s1.replaceAll("\\s", "").toLowerCase();
21+
s2 = s2.replaceAll("\\s", "").toLowerCase();
22+
23+
// Step 2: If lengths differ, can't be anagrams
24+
if (s1.length() != s2.length()) return false;
25+
26+
// Step 3: Sort and compare
27+
char[] arr1 = s1.toCharArray();
28+
char[] arr2 = s2.toCharArray();
29+
Arrays.sort(arr1);
30+
Arrays.sort(arr2);
31+
32+
return Arrays.equals(arr1, arr2);
33+
}
34+
}

02-strings/README.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,24 @@ Use two pointers (start and end), and check if characters match while moving inw
2323

2424
**Time Complexity:** O(n)
2525
**Space Complexity:** O(1)
26+
27+
---
28+
29+
### 🔤 Anagram Check
30+
31+
**Problem:**
32+
Check whether two strings are anagrams of each other.
33+
34+
**Input:** "listen", "silent"
35+
**Output:** true
36+
**Explanation:** Both have same letters in different order
37+
38+
**Approach:**
39+
- Clean the strings (remove spaces and convert to lowercase)
40+
- Sort both strings
41+
- Compare the sorted versions
42+
43+
**Time Complexity:** O(n log n)
44+
**Space Complexity:** O(n)
45+
46+
---

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy