Skip to content

Commit aa6683b

Browse files
committed
palindrome/anagram check snippets
1 parent d532525 commit aa6683b

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
---
2+
title: Check Anagram
3+
description: Checks if two strings are anagrams, meaning they contain the same characters ignoring order, spaces and case sensitivity
4+
author: Mcbencrafter
5+
tags: string,anagram,compare,arrays
6+
---
7+
8+
```java
9+
import java.util.Arrays;
10+
11+
public static boolean isAnagram(String text1, String text2) {
12+
String text1Normalized = text1.replaceAll("\\s+", "");
13+
String text2Normalized = text2.replaceAll("\\s+", "");
14+
15+
if (text1Normalized.length() != text2Normalized.length())
16+
return false;
17+
18+
char[] text1Array = text1Normalized.toCharArray();
19+
char[] text2Array = text2Normalized.toCharArray();
20+
Arrays.sort(text1Array);
21+
Arrays.sort(text2Array);
22+
return Arrays.equals(text1Array, text2Array);
23+
}
24+
25+
// Usage:
26+
System.out.println(isAnagram("listen", "silent")); // true
27+
System.out.println(isAnagram("hello", "world")); // false
28+
```
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
title: Check Palindrome
3+
description: Checks if a string reads the same backward as forward, ignoring whitespaces and case sensitivity
4+
author: Mcbencrafter
5+
tags: string,palindrome,compare,reverse
6+
---
7+
8+
```java
9+
public static boolean isPalindrome(String text) {
10+
String cleanText = text.toLowerCase().replaceAll("\\s+", "");
11+
12+
return new StringBuilder(cleanText)
13+
.reverse()
14+
.toString()
15+
.equals(cleanText);
16+
}
17+
18+
// Usage:
19+
System.out.println(isPalindrome("A man a plan a canal Panama")); // true
20+
```

0 commit comments

Comments
 (0)