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.
s
String
만들기)i
번째 문자와 n - 1 - i
번째 문자가 같은지 확인 (n
: 다듬어진 문자열 길이)class Solution {
public boolean isPalindrome(String s) {
StringBuilder sb = new StringBuilder();
for (char ch : s.toLowerCase().toCharArray()) {
if (('a' <= ch && ch <= 'z' || '0' <= ch && ch <= '9')) {
sb.append(ch);
}
}
char[] palindrome = sb.toString().toCharArray();
for (int i = 0; i < palindrome.length / 2; i++) {
if (palindrome[i] != palindrome[palindrome.length - 1 - i]) {
return false;
}
}
return true;
}
}
s.toLowerCase()
, string.toCharArray()
, StringBuilder
을 통해 중간중간에 생성하는 String
객체가 꽤 많다.double pointer 방법을 이용
complexity
개선 사항
String
객체 생성을 하지 않아 시간과 메모리 사용량이 줄어듦class Solution {
public boolean isPalindrome(String s) {
int front = 0;
int behind = s.length() - 1;
while(front < behind) {
if (!isAlphanumeric(s.charAt(front))) {
front++;
continue;
}
if (!isAlphanumeric(s.charAt(behind))) {
behind--;
continue;
}
if (!isSameLetter(s.charAt(front), s.charAt(behind))) {
return false;
}
front++;
behind--;
}
return true;
}
private boolean isAlphanumeric(char letter) {
return 'A' <= letter && letter <= 'Z'
|| 'a' <= letter && letter <= 'z'
|| '0' <= letter && letter <= '9';
}
private boolean isSameLetter(char letter1, char letter2) {
if ('0' <= letter1 && letter1 <= '9') {
return letter1 == letter2;
}
return letter1 == letter2
|| letter1 - letter2 == 'A' - 'a'
|| letter1 - letter2 == 'a' - 'A';
}
}