题目1153:括号匹配问题
来源:互联网 发布:淘宝量身定做羊绒衫 编辑:程序博客网 时间:2024/05/21 10:44
- 题目描述:
在某个字符串(长度不超过100)中有左括号、右括号和大小写字母;规定(与常见的算数式子一样)任何一个左括号都从内到外与在它右边且距离最近的右括号匹配。写一个程序,找到无法匹配的左括号和右括号,输出原来字符串,并在下一行标出不能匹配的括号。不能匹配的左括号用"$"标注,不能匹配的右括号用"?"标注.
- 输入:
输入包括多组数据,每组数据一行,包含一个字符串,只包含左右括号和大小写字母,字符串长度不超过100。
注意:cin.getline(str,100)最多只能输入99个字符!
- 输出:
对每组输出数据,输出两行,第一行包含原始输入字符,第二行由"$","?"和空格组成,"$"和"?"表示与之对应的左括号和右括号不能匹配。
- 样例输入:
)(rttyy())sss)(
- 样例输出:
)(rttyy())sss)(? ?$
C++代码:
#include<iostream>#include<stack>#include<string>using namespace std;int main(){stack<char>s;char result[101];char str[101];while(cin.getline(str,101)){int i;cout<<str<<endl; //Êä³ö½á¹ûfor(i=0;str[i]!='\0';i++){if('('==str[i]){s.push('(');result[i]=' ';}//ifelse if(')'==str[i]){if(s.empty())result[i]='?';else{s.pop();result[i]=' ';}//else}//else ifelseresult[i]=' '; //ÊÇ×ÖĸµÄ»°£¬´òÓ¡¿Õ¸ñ}//for//µ½ÕâÀïÖ»ÊÇÍê³ÉÁ˶ԡ°£©¡±ÓÒÀ¨ºÅµÄÌæ»»//cout<<result<<endl;result[i]='\0';int j=0;while(!s.empty()){i--;if(str[i]==')')j++;if('('==str[i]){if(0==j){result[i]='$';s.pop();}//ifelse{j--;}//else}//if}//whilecout<<result<<endl;}//whilereturn 1;}
Java代码:
package oj1153;import java.util.Scanner;import java.util.Stack;public class Main{public static void main(String args[]){//Vector<Character> s = null;Stack<Character> s=new Stack<>();Scanner in=new Scanner(System.in);char [] result=new char[101];while(in.hasNext()){s.clear();String str=in.nextLine(); //获取输入数据System.out.println(str);char temp[]=str.toCharArray();int i=0;for(;i<temp.length;i++){if('('==temp[i]){s.push('(');result[i]=' ';}//ifelse if(')'==temp[i]){if(s.empty()){result[i]='?';}//ifelse{s.pop();result[i]=' ';}//else}//else ifelse result[i]=' ';}//forint j=0;while(!(s.empty())){i--;if(')'==temp[i])j++;if('('==temp[i]){if(0==j){result[i]='$';s.pop();}else {j--;}}//if}//whileSystem.out.println(result);}//while}//main}//Main
0 0
- 题目1153:括号匹配问题
- 题目1153:括号匹配问题
- 题目1153:括号匹配问题
- 题目1153:括号匹配问题
- 题目1153:括号匹配问题
- 题目1153:括号匹配问题
- 题目1153:括号匹配问题
- 题目1153:括号匹配问题 题目26
- 【九度】题目1153:括号匹配问题
- 九度题目1153:括号匹配问题
- 九度题目1153:括号匹配问题
- 26-题目1153:括号匹配问题
- 九度题目1153括号匹配问题
- 题目1153:括号匹配问题[栈]
- 【九度】题目1153:括号匹配问题
- jobdu 题目1153:括号匹配问题
- 题目26:括号匹配问题
- 题目26:括号匹配问题
- Python数据类型之列表
- 字符串反转
- 直接拿来用!十大Material Design开源项目
- 阿里巴巴实习生负一天
- 开始写技(xue)术(xi)博(bi)客(ji)
- 题目1153:括号匹配问题
- How to make a sprite from URL in cocos2d-x
- LeetCode Unique Paths II
- Maven的pom.xml介绍
- Maven简介(六)——Dependency
- STC不断电下载
- 黑马程序员-OC语言-创建一个对象并访问成员变量(听课笔记)
- Maven简介(二)——使用Maven
- github android 项目地址