牛客_草稿笔记
題目:
關于匹配輸入的英文字符串中,如果是兩個”("和“)"就將其中的字符屏蔽掉,如果遇到了“<"就將前面的一個字符屏蔽掉,已知括號都是成對出現。
比如 輸入 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);} }?
總結
- 上一篇: 九.项目采购管理
- 下一篇: 数据中心机房人员定位系统