문제
- 주어진 문자열이 팰린드롬인지 확인하라. 대소문자를 구분하지 않으며, 영문자와 숫자만을 대상으로 한다.
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.
class Solution {
public:
bool isPalindrome(string s) {
string temp;
string S_reverse;
bool ans;
int a;
for (int i = 0; i < s.size(); i++)
{
//S문자의 i번째 단어가 알파벳 or 숫자일때 if true
if (isalpha(s[i]) != 0 || isdigit(s[i]) != 0)
{
//해당 단어를 소문자로 바꿔준다.
//temp끝에 해당 단어를 추가 한다.
s[i] = tolower(s[i]);
temp.push_back(s[i]);
}
}
//S_reverse에 temp를 할당
S_reverse.assign(temp);
//S_reverse를 뒤집어 준다.
reverse(S_reverse.begin(), S_reverse.end());
//temp와 뒤집은 S_reverse를 비교후 맞다면 true 출력
if (temp.compare(S_reverse) == 0) return ans = true;
else
return ans = false;
}
};
Runtime 7 ms / Memory 8 MB
https://leetcode.com/problems/valid-palindrome/submissions/879931528/