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.
Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.
Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.
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.
s consists only of printable ASCII characters.
처음에는 조건문을 많이 걸어서 코드를 돌리려고 했다.
그러다가 불용어를 뺀 문자를 구분해서 char[]에 따로 저장하면서 count를 센다.
그리고 저장한 메모리에서 left++/right--하면서 비교해 나간다.
주의할 점은, 문자에 숫자도 포함된다!
//https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/883/
class Solution {
public boolean isPalindrome(String s) {
if (s.length() == 1) return true;
s = s.toLowerCase();
byte[] ascii = new byte[s.length()];
int count = 0;
for (int i = 0; i < s.length(); i++) {
char temp = s.charAt(i);
if (temp >= 'a' && temp <= 'z' || temp >= '0' && temp <= '9') {
ascii[count++] = (byte) (s.charAt(i));
}
}
int left = 0;
int right = count - 1;
while (left <= right) {
if (ascii[left] != ascii[right])
return false;
left++;
right--;
}
return true;
}
Tip
Character.isLetterOrDigit()