https://oj.leetcode.com/problems/valid-palindrome/
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,"A man, a plan, a canal: Panama"
is a palindrome."race a car"
is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
//empty string = valid
//extra memory = none
//only alphabet case
//solution : two runner(head, end) 끝에서부터 서로 비교하면서 만날때까지 증감.
//time complexity : O(2n)
//test case : "", " ", "a", "aba", "abcba", "a a baa", "a b c d e"
class Solution {
public:
bool isPalindrome(string s) {
if(s.length() <= 1) return true;
transform(s.begin(), s.end(), s.begin(),::tolower);
std::string::iterator head = s.begin();
std::string::iterator tail = s.end();
tail--;
while(head < tail) {
while( !((*head >= '0' && *head <= '9') || (*head >= 'a' && *head <= 'z')) && (head < tail) ) {
head++;
}
while( !((*tail >= '0' && *tail <= '9') || (*tail >= 'a' && *tail <= 'z')) && (head < tail) ) {
tail--;
}
if(*head != *tail) return false;
else {
head++;
tail--;
}
}
return true;
}
'풀어본 Algorithm 문제 정리' 카테고리의 다른 글
[OJ.leetcode] Validate Binary Search Tree (0) | 2014.06.29 |
---|---|
[OJ.leetcode] Convert Sorted Array to Binary Search Tree (0) | 2014.06.29 |
[OJ.leetcode] Search Insert Position (0) | 2014.06.29 |
[OJ.leetcode] Linked List Cycle (0) | 2014.06.29 |
[OJ.leetcode] Evaluate Reverse Polish Notation (0) | 2014.06.29 |