第一题:计算圆括号的配对数、落单左括号数、落单右括号数
import java.util.*;
public class Main_1 {
public static void isMatch(String s)
{
int count1 = 0;
int count2 = 0;
int count3 = 0;
Map<Character, Character> map = new HashMap<>();
map.put(')', '(');
Stack<Character> stack = new Stack<>();
for(int i = 0; i < s.length(); i++)
{
Character temp = s.charAt(i);
if(map.containsValue(temp))
{
stack.push(temp);
count2++;
}
else if(map.containsKey(temp))
{
if(stack.isEmpty())
{
count3++;
continue;
}
if(stack.peek() == map.get(temp))
{
stack.pop();
count1++;
count2--;
}
else
{
count3++;
}
}
}
System.out.println(count1 + " " + count2 + " " + count3);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine())
{
String str = sc.nextLine();
isMatch(str);
return;
}
}
}
参考1:
- 4AC快手笔试4.12
- 2020快手笔试 4.12
- 快手笔试这么简单吗?
参考2:
- Java实现括号是否匹配(给定一串字符串看括号是否成对出现)
- Java 用栈解决括号匹配问题
- 括号配对问题JAVA实现
- 括号匹配算法的一种正确实现(java)
- 栈的应用----判断括号是否匹配
- 【stack使用-括号匹配问题】