Skip to content

Commit c9df170

Browse files
committed
Solve valid-palindrome in two-way
1 parent b54e8b2 commit c9df170

1 file changed

Lines changed: 84 additions & 0 deletions

File tree

valid-palindrome/OstenHun.cpp

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
/*
2+
A phrase is a palindrome if,
3+
after converting all uppercase letters into lowercase letters and
4+
removing all non-alphanumeric characters, it reads the same forward and backward.
5+
Alphanumeric characters include letters and numbers.
6+
7+
Given a string s, return true if it is a palindrome, or false otherwise.
8+
9+
Example 1:
10+
11+
Input: s = "A man, a plan, a canal: Panama"
12+
Output: true
13+
Explanation: "amanaplanacanalpanama" is a palindrome.
14+
15+
Constraints:
16+
17+
1 <= s.length <= 2 * 105
18+
s consists only of printable ASCII characters.
19+
*/
20+
21+
#include <cctype>
22+
#include <string>
23+
#include <vector>
24+
using namespace std;
25+
26+
#pragma region ExtraSpaceIdea
27+
// 새로운 배열을 만들어서 문자열을 정리한 후에 팰린드롬 판별
28+
// 시간 복잡도 : O(n)
29+
// 공간 복잡도 : O(n)
30+
// n은 문자열의 길이일 것이다.
31+
namespace extra_space_idea {
32+
33+
class Solution {
34+
public:
35+
bool isPalindrome(string s) {
36+
vector<char> str;
37+
str.reserve(s.size());
38+
39+
size_t len = s.length();
40+
for (size_t i = 0; i < len; i++) {
41+
if (isalnum(s[i])) {
42+
str.push_back(tolower(s[i]));
43+
}
44+
}
45+
46+
size_t vec_len = str.size();
47+
for (size_t i = 0; i < (vec_len + 1) / 2; i++) {
48+
if (str[i] != str[vec_len - 1 - i]) return false;
49+
}
50+
51+
return true;
52+
}
53+
};
54+
55+
} // namespace extra_space_idea
56+
#pragma endregion
57+
58+
#pragma region FinalSolution
59+
// 투 포인터를 이용해 추가 배열 없이 구현
60+
// 시간 복잡도 : O(n)
61+
// 공간 복잡도 : O(1)
62+
class Solution {
63+
public:
64+
bool isPalindrome(string s) {
65+
int left = 0;
66+
int right = s.length() - 1;
67+
68+
while(left < right) {
69+
if (!isalnum(s[left]))
70+
left++;
71+
else if (!isalnum(s[right]))
72+
right--;
73+
else {
74+
if (tolower(s[left]) != tolower(s[right]))
75+
return false;
76+
left++;
77+
right--;
78+
}
79+
}
80+
81+
return true;
82+
}
83+
};
84+
#pragma endregion

0 commit comments

Comments
 (0)