Skip to content

Instantly share code, notes, and snippets.

@walkingtospace
Last active August 29, 2015 14:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save walkingtospace/42d13d24f4778e68d7e1 to your computer and use it in GitHub Desktop.
Save walkingtospace/42d13d24f4778e68d7e1 to your computer and use it in GitHub Desktop.
valid-palindrome 문제
//https://oj.leetcode.com/problems/valid-palindrome/
//empty string = valid
//extra memory = none
//only alphanumeric 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(!(isdigit(*head) || isalpha(*head)) && (head < tail) ) head++;
while(!(isdigit(*head) || isalpha(*head)) && (head < tail) ) tail--;
if(*head != *tail) return false;
else {
head++;
tail--;
}
}
return true;
}
};
@coderiff
Copy link

coderiff commented Jun 4, 2014

isalpha(), isdigit()을 사용하면 어떨지요?

@walkingtospace
Copy link
Author

제가 아직 api를 다모르다보니.. 있을것이라 짐작은 했는데 있었군요 ^^; 감사합니다

@walkingtospace
Copy link
Author

isdigit, isalpha() 함수가 < cctype > 에 포함되어있으므로 사용하도록 변경

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment