L1-064 估值一亿的核心代码

文章介绍了使用C++编写的一段代码,通过栈操作对输入的字符串进行规范化处理,包括去除空格、低化字母、替换I和me为you以及统一couldyou为Icould。展示了如何在编程中模拟简单的AI文本转换过程。
摘要由CSDN通过智能技术生成

思路:去掉空格可以考虑用手写stack,速度块而且逻辑简单,还要考虑操作之间的冲突,比如我把‘I’和"me"改成"you"之后有可能生成原文不存在的“can you",所以我们可以先把其改成”YOU“---------(这是笨蒟蒻好久之前看过的别的佬的一个小trik)

#include<bits/stdc++.h>
using namespace std;
int n;
string s[20],s2[20];
char stack_s[2010];
int tot;
void qkg(int id)
{
	string cur=s[id];
	tot=0;
	int st=0,len=cur.size();
	while(st<len&&cur[st]==' ') st++;
	for(int i=st;i<len;i++)
	{
		if(cur[i]==' ')
		{
			if(stack_s[tot]==' ') continue;
			else stack_s[++tot]=cur[i];
		}
		else if(isalnum(cur[i])) stack_s[++tot]=cur[i];
		else{
			while(tot&&stack_s[tot]==' ') tot--;
			if(cur[i]=='?')  cur[i]='!';
			stack_s[++tot]=cur[i];
		}
	} 
	while(tot&&stack_s[tot]==' ') tot--;
	string tem;
	while(tot) tem+=stack_s[tot--];
	reverse(tem.begin(),tem.end());
	s[id]=tem;
}
void tolow(int id)
{
	string cur=s[id];
	int st=0,len=cur.size();
	for(int i=st;i<len;i++)	if(isalpha(cur[i])){
		if(cur[i]=='I') continue;
	    cur[i]=tolower(cur[i]);
	}
	s[id]=cur;
}
void changeime(int id)
{
	string cur=s[id];
	tot=0;
	int st=0,len=cur.size();
	string u="YOU";
	for(int i=st;i<len;i++)
	{
		if((!i||!isalnum(cur[i-1]))&&cur[i]=='I'&&(i==len-1||!isalnum(cur[i+1]))) 
		{
			//string u="YOU";
		  for(auto v:u)	stack_s[++tot]=v;
		}
		else{
		//	string u="YOU";
			if((!i||!isalnum(cur[i-1]))&&cur.substr(i,2)=="me"&&(i==len-2||!isalnum(cur[i+2]))){
				for(auto v:u) stack_s[++tot]=v;
				i++;
			}
			else stack_s[++tot]=cur[i];
		}
	}
	string tem;
	while(tot) tem+=stack_s[tot--];
	reverse(tem.begin(),tem.end());
	s[id]=tem;
}
void changecouldyou(int id)
{
	tot=0;
	string cur=s[id];
	int st=0,len=cur.size();
	for(int i=st;i<len;i++)
	{
		string uk=cur.substr(i,7);
		string uk2=cur.substr(i,9);
		if((!i||!isalnum(cur[i-1]))&&uk=="can you"&&(i==len-7||!isalnum(cur[i+7])))
		{
			string y="I can";
			for(auto v:y) stack_s[++tot]=v;
			i+=6;
		}
		else if((!i||!isalnum(cur[i-1]))&&uk2=="could you"&&(i==len-9||!isalnum(cur[i+9])))
		{
			string y="I could";
			for(auto v:y) stack_s[++tot]=v;
			i+=8;
		}
		else stack_s[++tot]=cur[i];
	}
	string tem;
	while(tot) tem+=stack_s[tot--];
	reverse(tem.begin(),tem.end());
	s[id]=tem;
}
int main()
{
	cin>>n;
	getchar();
	for(int i=1;i<=n;i++) getline(cin,s[i]),s2[i]=s[i];
	for(int i=1;i<=n;i++)
	{
		qkg(i);
		tolow(i);
		changeime(i);
		changecouldyou(i);
	}
	for(int i=1;i<=n;i++)
	{
		cout<<s2[i]<<'\n';
		cout<<"AI: ";
		for(auto v:s[i])
		{
			//cout<<(char)tolower(v);
			if(isalnum(v))
			{
				if(v=='I') cout<<v;
				else cout<<(char)tolower(v);
			}
			else cout<<v;
		}
		cout<<'\n';
	}
    return 0;	
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值