正则表达式
类型判断
std::regex rx("[0-9]+");
bool bl = std::regex_match(str.begin(),str.end(), rx);
常用方法
类型判断
str.find_first_not_of(“0123456789”) == std::string::npos
std::all_of(str.begin(), str.end(), ::isdigit); // C++11,lambda表达式
旋转词
word.substr(n, word.length()) << word.substr(0, n);
str.find(R_str) != string::npos // -->KMP算法内容?
字符统计
数组字符值为数组索引,或者set之类的时间复杂度O(N),满足时间O(N)的排序
字符种类过多的情况下,用哈希表代替。set。
如果空间复杂度要求O(1),考虑比较排序类的算法对原数组进行排序。
字符串转数字
stoi(),注意int越界,注意判别非法输入。
回文字符串
中心扩展法,插入额外辅助符号, 时间复杂度O(n2),可能超时:
#include<iostream>
#include<vector>
#include<cctype>
#include<string>
using namespace std;
int palindrome(string temp, int iCentre){
int length = 0;
for(int i = 1; i <= temp.size(); i++){
if(iCentre - i >= 0 && iCentre + i < temp.size()){
if(temp[iCentre - i] == temp[iCentre + i]){
length += 1;
}
else{
break;
}
}
else{
break;
}
}
return length;
}
int main() {
string str;
string temp;
int maxLength = 0;
while(cin >> str){
maxLength = 0;
for(auto & x : str){
temp.push_back('#');
temp.push_back(x);
}
temp.push_back('#');
for(int iCentre = 0; iCentre < temp.size(); iCentre++){
maxLength = max(maxLength, palindrome(temp, iCentre));
}
cout << maxLength;
}
return 0;
}