Skip to content

Commit e21e208

Browse files
authored
Merge pull request #4 from xchux/feature/125-valid-palindrome
✨ 125. Valid Palindrome
2 parents f063e53 + ed7aba2 commit e21e208

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
---
2+
comments: true
3+
difficulty: easy
4+
# Follow `Topics` tags
5+
tags:
6+
- String
7+
- Two Pointers
8+
---
9+
10+
# [125. Valid Palindrome](https://leetcode.com/problems/valid-palindrome/description/)
11+
12+
## Description
13+
14+
A palindrome is a sequence that reads the same forward and backward.
15+
16+
For this problem, a string is considered a palindrome if:
17+
18+
1. All uppercase letters are converted to lowercase.
19+
2. All non-alphanumeric characters (such as spaces, punctuation, and symbols) are removed.
20+
3. The remaining characters form a sequence that reads identically from both directions.
21+
22+
Your task is to check whether a given string meets these conditions and return true if it does, otherwise return false.
23+
24+
**Example 1:**
25+
```
26+
Input: Was it a car or a cat I saw?
27+
Output: true
28+
Explanation: "wasitacaroracatisaw" is a palindrome.
29+
```
30+
31+
**Example 2:**
32+
```
33+
Input: How are you?
34+
Output: false
35+
Explanation: "howareyou" is not a palindrome.
36+
```
37+
38+
**Constraints:**
39+
40+
`1 <= s.length <= 2 * 10^5`
41+
42+
`s consists only of printable ASCII characters.`
43+
44+
## Solution
45+
46+
Intuitively remove non-alphanumeric and change others to lowercase.
47+
48+
```java
49+
class Solution {
50+
public boolean isPalindrome(String s) {
51+
s = s.toLowerCase().replaceAll("[^a-z0-9]", "");
52+
int i = 0, j = s.length() - 1;
53+
while (i < j) {
54+
if (s.charAt(i++) != s.charAt(j--)) return false;
55+
}
56+
return true;
57+
}
58+
}
59+
```
60+
61+
## Complexity
62+
63+
- Time complexity: $$O(n)$$
64+
<!-- Add time complexity here, e.g. $$O(n)$$ -->
65+
66+
- Space complexity: $$O(n)$$
67+
<!-- Add space complexity here, e.g. $$O(n)$$ -->
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
class Solution {
2+
public boolean isPalindrome(String s) {
3+
s = s.toLowerCase().replaceAll("[^a-z0-9]", "");
4+
int i = 0, j = s.length() - 1;
5+
while (i < j) {
6+
if (s.charAt(i++) != s.charAt(j--)) return false;
7+
}
8+
return true;
9+
}
10+
}

0 commit comments

Comments
 (0)