牛客_草稿笔记
题目:
关于匹配输入的英文字符串中,如果是两个”("和“)"就将其中的字符屏蔽掉,如果遇到了“<"就将前面的一个字符屏蔽掉,已知括号都是成对出现。
比如 输入 abc<<(ab(a)<)a<
输出为a 因为两个括号已经将其中的内容屏蔽掉,剩下就是abc<<a< 再就是将前面的字符屏蔽掉,剩下a
分析:
利用一个栈,来进行括号中屏蔽数据的操作,使得栈中剩下的都是英语字母和”<",再对栈进行一次遍历,判断"<"的个数以及该屏蔽的英文字母的个数,最终输出
/*** @ Author zhangsf* @CreateTime 2019/9/3 - 7:33 PM*/ package com.bjut.qiu;import java.util.Scanner; import java.util.Stack;public class testString {public static void main(String args[]){Scanner sc = new Scanner(System.in);//定义一个栈Stack<Character> a= new Stack<>();//字符串string长度nString string=sc.nextLine();//长度nint n=string.length();String outString ="";char[] c =string.toCharArray();//遍历char b<<b((b)<)for (int i = 0; i < n; i++) {//遇到右括号就开始出栈,直到匹配到左括号,因为括号是成对出现的if (c[i]==')'){char index=a.pop();//只要没有找到 左括号就一直出栈while (index!='(' && a.size()>0){index=a.pop(); }}else{//其他情况就开始入栈操作,最终栈中的元素不会有括号及其包括的的内容a.push(c[i]);}}//用来记录<<的个数int count=0;//遍历栈,移除<和后面的非'<'字母while (!a.isEmpty()){char index1=a.pop();if (index1=='<'){count++;}else{outString=index1+outString;}while(count>0&&!a.isEmpty()){//先去掉一个紧跟'<'后面的一个非<字符,若为'<' 就将count++if(a.pop()=='<') {count++;} else {count--;}}}System.out.println(outString);} }比如输入为 (acb<<)cbck<<,最终输出为cb
另一种解法:
不使用栈
/*** @ Author zhangsf* @CreateTime 2019/9/3 - 10:05 PM*/ package com.bjut.qiu;import java.util.Scanner;public class BJCJ_xhs {public static void main( String[] args ) {helper();}private static void helper() {Scanner sc = new Scanner(System.in);String s = sc.next();String res = "";int count = 0, len = s.length();for(int i=0;i<len;i++) {char c = s.charAt(i);if(c == '(') {count ++;}else if(c == ')') {count --;}else if(c == '<') {if(res.length() > 0 && count == 0 && res.charAt(res.length() - 1) != ')') {res = res.substring(0, res.length() - 1);}}else if(count == 0) {res += c;}}System.out.println(res);} }
总结
- 上一篇: 九.项目采购管理
- 下一篇: 【新书推荐】【2018.06】机载雷达信