[LeetCode 125] Valid Palindrome
LeetCode 125 (Java)
[Valid Palindrome] 문제 풀이
[LeetCode 125] Valid Palindrome
Description
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s, return true if it is a palindrome, or false otherwise.
Example 1
- Input: s = “A man, a plan, a canal: Panama”
- Output: true
- Explanation: “amanaplanacanalpanama” is a palindrome.
Example 2
- Input: s = “race a car”
- Output: false
- Explanation: “raceacar” is not a palindrome.
Example 3
- Input: s = “ “
- Output: true
- Explanation:
- s is an empty string “” after removing non-alphanumeric characters.
- Since an empty string reads the same forward and backward, it is a palindrome.
Constraints
1 <= s.length <= 2 * 10^5sconsists only of printable ASCII characters.
Code
내 제출
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public boolean isPalindrome(String s) {
int i = 0, j = s.length() - 1;
while (i < j) {
if (!Character.isLetterOrDigit(s.charAt(i))) {
++i;
} else if (!Character.isLetterOrDigit(s.charAt(j))) {
--j;
} else if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))) {
return false;
} else {
++i;
--j;
}
}
return true;
}
}
| Runtime | Memory |
|---|---|
| 2 ms | 43.3 MB |
다른 풀이
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public boolean isPalindrome(String s) {
s = s.toLowerCase();
s = s.replaceAll("[^a-z0-9]", "");
int left = 0;
int right = s.length() - 1;
while (left < right) {
if (s.charAt(left++) != s.charAt(right--))
return false;
}
return true;
}
}
Reference
- https://github.com/doocs/leetcode/blob/main/solution/0100-0199/0125.Valid%20Palindrome/Solution.java
This post is licensed under CC BY 4.0 by the author.
