描述
Little Hi is writing an algorithm lecture note for Little Ho. To make the note more comprehensible, Little Hi tries to color some of the text. Unfortunately Little Hi is using a plain(black and white) text editor. So he decides to tag the text which should be colored for now and color them later when he has a more powerful software such as Microsoft Word.
There are only lowercase letters and spaces in the lecture text. To mark the color of a piece of text, Little Hi add a pair of tags surrounding the text, <COLOR> at the beginning and </COLOR> at the end where COLOR is one of "red", "yellow" or "blue".
Two tag pairs may be overlapped only if one pair is completely inside the other pair. Text is colored by the nearest surrounding tag. For example, Little Hi would not write something like "<blue>aaa<yellow>bbb</blue>ccc</yellow>". However "<yellow>aaa<blue>bbb</blue>ccc</yellow>" is possible and "bbb" is colored blue.
Given such a text, you need to calculate how many letters(spaces are not counted) are colored red, yellow and blue.
输入
Input contains one line: the text with color tags. The length is no more than 1000 characters.
输出
Output three numbers count_red, count_yellow, count_blue, indicating the numbers of characters colored by red, yellow and blue.
样例输入
<yellow>aaa<blue>bbb</blue>ccc</yellow>dddd<red>abc</red>
样例输出
3 6 3
题意大概为,对一行文本进行着色区分<..>开始,</..>结束,统计三种不同颜色字母的个数,按红黄蓝输出。
很典型的栈的应用,也可以这么理解,最急迫事件原则,每次面对一个新颜色进栈,并且以后字母颜色计数都为对应的栈顶颜色计数,遇到出栈标记,栈顶元素出栈
AC--Java
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
//红黄蓝,三种颜色对应的字母个数
int reds = 0, yellows = 0, blues = 0;
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
char[] arr = str.toCharArray();
Stack<String> stack = new Stack<String>();
for (int i = 0; i < arr.length; i++) {
//不论出栈入栈,每次i都指向'>',以保证循环
if(arr[i] == '<'&&arr[i + 1] != '/') {//入栈标记
i++;
StringBuilder sb = new StringBuilder();
while(arr[i] != '>') {
sb.append(arr[i]);
i++;
}
stack.push(sb.toString());//颜色进栈
}else if(arr[i] == '<'&&arr[i + 1] == '/') {//出栈标记
while(arr[i] != '>')
i++;
stack.pop();
}else {//单词,对应栈顶颜色记录个数,如果栈为空继续循环
if(stack.isEmpty())
continue;
else {
if(stack.peek().equals("red"))
if(arr[i] != ' ')
reds++;
if(stack.peek().equals("yellow"))
if(arr[i] != ' ')
yellows++;
if(stack.peek().equals("blue"))
if(arr[i] != ' ')
blues++;
}
}
}
System.out.println(reds + " " + yellows + " " + blues);
}
}
网友评论