문장이 회문(palindrome)인지를 판단하려면, 모든 대문자를 소문자로 변환하고 모든 비알파벳 및 비숫자 문자를 제거한 후, 그 문장이 앞으로 읽으나 뒤로 읽으나 동일하게 읽히면 회문입니다. 알파벳과 숫자 문자를 알파뉴메릭(Alphanumeric) 문자라고 합니다.
문자열 s가 주어졌을 때, 이 문자열이 회문이면 true를, 그렇지 않으면 false를 반환하세요.
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.
class Solution {
public boolean isPalindrome(String s) {
// 1. replaceAll 함수와 정규표현식을 이용하여 비알파벳 제거 및 소문자로 변환
s = s.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
// 2. two pointer 생성하기
int left = 0;
int right = s.length() -1;
// 3. 두 포인터가 가리키는 문자를 비교
while (left < right) {
if (s.charAt(left) != s.charAt(right)) { // 같지 않으면 false
return false;
}
left++; // 왼쪽으로 포인터 이동
right--; // 오른쪽으로 포인터 이동
}
return true;
}
}