LeetCode 125. Valid Palindrome
Solution1:我的答案
复杂度为 O(n) O ( n ) ,写法不是很简练啊。
class Solution {
public:
bool isPalindrome(string s) {
int n = s.size();
if (n <= 1) return true;
//均转换为小写
transform(s.begin(), s.end(), s.begin(), ::tolower);
int i = 0, j = n - 1;
while (i < j) {
if (!(s[i] >= 48 && s[i] <= 57 || s[i] >= 97 && s[i] <= 122)) {
i++;
continue;
}
if (!(s[j] >= 48 && s[j] <= 57 || s[j] >= 97 && s[j] <= 122)) {
j--;
continue;
}
if (s[i] != s[j])
return false;
else if (s[i] == s[j]) {
i++;
j--;
}
}
return true;
}
};
tips:
1)用isalnum()函数判断是否是数字或字母会使代码更简洁,关于此类函数的两个链接:
[1]https://blog.csdn.net/Dawn_sf/article/details/62416188
[2]https://blog.csdn.net/liuchuo/article/details/54602567
2)对于该问题的扩展,还有利用Manacher算法(马拉车算法)来求解最长回文字符串问题,参考链接:
http://www.cnblogs.com/grandyang/p/4475985.html
C++ string的大小写转换
参考网址:https://www.cnblogs.com/balingybj/p/4678850.html
STL的algorithm库确实给我们提供了这样的便利,使用模板函数transform可以轻松解决这个问题,开发人员只需要提供一个函数对象,例如将char转成大写的toupper函数或者小写的函数tolower函数。
示例代码:
transform原型:
template < class InputIterator, class OutputIterator, class UnaryOperator >
OutputIterator transform ( InputIterator first1, InputIterator last1,
OutputIterator result, UnaryOperator op );
template < class InputIterator1, class InputIterator2,
class OutputIterator, class BinaryOperator >
OutputIterator transform ( InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, OutputIterator result,
BinaryOperator binary_op );
示例代码:
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string strA = "yasaken@126.com";
string strB = "LURY@LENOVO.com";
printf("Before transform:\n");
printf("strA:%s \n", strA.c_str());
printf("strB:%s \n\n", strB.c_str());
transform(strA.begin(), strA.end(), strA.begin(), ::toupper);//重点
transform(strB.begin(), strB.end(), strB.begin(), ::toupper);//重点
printf("After transform to toupper:\n");
printf("strA:%s \n", strA.c_str());
printf("strB:%s \n\n", strB.c_str());
transform(strA.begin(), strA.end(), strA.begin(), ::tolower);//重点
transform(strB.begin(), strB.end(), strB.begin(), ::tolower);//重点
printf("After transform to lower:\n");
printf("strA:%s \n", strA.c_str());
printf("strB:%s \n\n", strB.c_str());
return 0;
}
运行结果:
strA:yasaken@126.com
strB:LURY@LENOVO.com
After transform to toupper:
strA:YASAKEN@126.COM
strB:LURY@LENOVO.COM
After transform to lower:
strA:yasaken@126.com
strB:lury@lenovo.com