通过栈实现字符串中查找是否有指定字符串的存在

题目示例:
在这里插入图片描述

分析

由与没有给出字符串的长度,所以只能通过getline一次性处理,而在输入后恰好能倒序处理字符串,以标点符号为分界点,将数字当成字符放到栈里,遇到下一个标点符号时执行查找操作,并清空栈。

题不难,直接上代码实现吧:


//程序没考虑空格。请用这行没空格的样例 
//样例: matrix=[[1,3,5,7],[10,11,16,20],[23,30,34,60]],target=3
//matrix=[[1,3,5,7],[10,11,16,20],[23,30,34,60]],target=11


#include <iostream>
#include <string>
#include <cstring>
#include <stack>
using namespace std;

stack<char> c;

char tar[1000];

bool ans;

void del()
{
	while (!c.empty())
	{
		c.pop();
	}
}

bool equ(int t, char ss[], char s[])
{
	for (int i = 0; i<=t ; i++)
	{
		if (s[i] != ss[i])
		{
			return false;
		}
	}
	return true;
}

bool com()
{
	char b[10000]={'\0'};
	int i = 0;
	
	while (!c.empty())
	{
		b[i] = c.top();
		c.pop();
		i++;
//		cout<<"cbb "<<b[i]<<" this"<<endl;
		
	}
	
//	cout<<"ans"<<tar<<" "<<b<<endl;
	
	if (equ(i, b, tar))
	{
		ans = true;
		
//		cout<<"ans"<<tar<<" "<<b<<endl;
		
		return ans;
	}
	
	return false;
}

int main()
{
	string a;
	
	getline(cin,a);
	
	int n = a.size();
	
	int x = n;
	
	char temp = a[n-1];
	
	while (temp != '=')
	{
		n--;
		temp = a[n-1];
//		cout<<n<<endl;
	} 

	for (int i = n, j = 0;i <= x-1; i++,j++)
	{
		tar[j] = a[i];
//		cout<<"t"<<a[i]<<endl;
	}//提取目标字符串 
	
//	cout<<"tar"<<tar<<endl;
	
	n--;//减去等号
	n--;//再减1直接拿n当下标
	n-=6;//减去target 
	
//	cout<<"a[n]"<<a[n]<<endl;
	
	while (a[n] != '=')
	{
		if (a[n] == ']')
		{
			n--;
			continue;
		} 
		if (a[n] == ',' || a[n] == '[')
		{
//			cout<<"where"<<endl;
			if (!c.empty())
			{
				if (com())
				{
					break;
				}
			}
			n--;
			continue;
		}
		c.push(a[n]);
		
//		cout <<"n"<< n<<" "<<a[n]<<" ";
		
		n--;
	} 
	
	if (ans == true)
	{
		cout<<"true";
	}else
	{
		cout<<"false";
	}
	
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值