c++字符串括号匹配 | 栈的应用

Question

  1. 请编写程序对一段程序代码中的括号匹配情况进行判断。括号类型有(),[],{}三类
  2. 程序代码中可能包含注释和双引号,如多行注释/**/和单行注释//,且引号和注释中的内容不参与括号匹配情况的分析。

Description

Input
若干行程序代码,代码长度小于1500个字符
Output
除去注释后的括号数量 括号是否匹配(yes/no)

Example

//1
input
int Collatz(unsigned int n) {
    if(n==1) return 0;
    else if(n%2) return Collatz(n*3+1)+1;
    else return Collatz(n/2)+1;
}
output
12 yes

//2
input
float CalcPay( /* [in] */  float  payRate,     // Employee's pay rate
              /* [in] */  float  hours      // Hours worked
               ){     //return Wages earned()
output
3 no

//3
input
"//" ()
output
2 yes

Code

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

int main() {
	stack<char>s;
	char str[1500];
	char n;

	char symbol, match;
	bool ismatch = true;
	bool inside_quotes = false; //在引号里
	bool inside_slashes = false; //在双斜线里
	bool inside_notes = false; //在注释里
	
	int cnt = 0;

	//把字符串存入数组
	int j = 0;
	while ((n = cin.get()) != EOF)
	{
		str[j++] = n;
	}
	str[j] = '\0';

	//开始读取
	int i = 0;
	while (str[i] != '\0')
	{
		//检验是否在引号内
		if (str[i] == '"' && inside_quotes == false)
			inside_quotes = true;
		else
		    if (str[i] == '"' && inside_quotes == true)
				inside_quotes = false;
        
        
        //检验是否在注释里
		if ((str[i] == '/' && str[i + 1] == '/') && inside_quotes == false)
			inside_slashes = true;
		if ((str[i] == '/' && str[i + 1] == '*') && inside_quotes == false)
			inside_notes = true;
			
		if ((str[i] == '\n' && inside_slashes))
			inside_slashes = false;
		if ((str[i] == '*' && str[i + 1] == '/'))
			inside_notes = false;


		//开始检验括号匹配
		symbol = str[i];
		if (symbol == '(' || symbol == '[' || symbol == '{') {
			s.push(symbol);
			if (!(inside_slashes || inside_notes))
				cnt++;
		}
		if (symbol == ')' || symbol == ']' || symbol == '}') {
			if (!(inside_slashes || inside_notes))
				cnt++;
			if (s.empty())
				ismatch = false;
			else
			{
				match = s.top();
				s.pop();
				ismatch = (
					(match == '(' && symbol == ')') ||
					(match == '[' && symbol == ']') ||
					(match == '{' && symbol == '}'));
			}
		}
		i++;
	}
	
	//循环结束 检验匹配完之后栈是否为空
	if (!s.empty())
		ismatch = false;

	if (ismatch)
		cout << cnt << " yes" << endl;
	else
		cout << cnt << " no" << endl;

	return 0;
}
发布了13 篇原创文章 · 获赞 0 · 访问量 266

猜你喜欢

转载自blog.csdn.net/Caiyii530/article/details/104987293