关于字符串的一些操作

正则表达式

类型判断

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
数据结构课程设计简易运算器 #include #include #include #include #include #include using namespace std; char str[50]; //用于存放原来的表达式 int top; //栈顶指针 char stack[50]; //定义栈,用于计算逆波兰式 char ex[50]; //存放后缀表达式 double _stack[50]; //定义栈,用于计算逆波兰式子 int flag[50]; //用于区分+、-号的含义,0表示运算符,1表示正负号 //生成逆波兰式 void NiBolan() { memset(flag,0,sizeof(flag)); //flag初始值设为0 char ch=str[0]; int i=1,t=0; top=0; while(ch!='#') { switch(ch) { case '(': top++; stack[top]=ch; break; case ')': while(stack[top]!='(') { ex[t]=stack[top]; top--; t++; } top--; break; case '^': while(stack[top]=='^') //设置^运算符优先级为最高 { ex[t]=stack[top]; top--; t++; } top++; stack[top]=ch; break; case '+': case '-': //当ch为+、-号是,若前面相邻字符不是')'或数字且后面相邻字符是数字时表示正负号 if(isdigit(str[i]) && !isdigit(str[i-2]) && str[i-2]!=')') { flag[t]=1; //标记符号为正负号 ex[t++]=ch; ch=str[i++]; while((ch>='0'&&ch;='0'&&ch;='0'&&ch;='0'&&ch;='0'&&ch;='0'&&ch;='0'&&ch;='0'&&ch;<='9') { d=d+double(ch-'0')/(10.0*k); k=k+1.0; ch=ex[++t]; } } top++; _stack[top]=d; } ch=ex[t]; } cout<<"计算出的结果:"<<_stack[top]<<endl; //printf("计算出的结果:%lf\n",_stack[top]); } int main() { printf("输入中缀表达式:"); scanf("%s",&str;); //输入原表达式 printf("原来的表达式:%s\n",str); NiBolan(); //生成逆波兰式 Calculate(); //计算逆波兰式 return 0; }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值