Skip to content

Instantly share code, notes, and snippets.

@kishida
Last active January 22, 2016 16:59
Show Gist options
  • Save kishida/149c20f82530fb5a38b1 to your computer and use it in GitHub Desktop.
Save kishida/149c20f82530fb5a38b1 to your computer and use it in GitHub Desktop.
Retrieve a pair of parenthesis with Stack.
package javaapplication1.beginer;
import java.util.LinkedList;
/**
*
* @author naoki
*/
public class AaaParenthesis {
public static void main(String[] args) {
String aaa = "aaa(aaa(aa((aaa)aa))aa)a";
LinkedList<Integer> stack = new LinkedList<>();
for(int i = 0; i < aaa.length(); ++i){
char ch = aaa.charAt(i);
switch(ch){
case 'a':
// do nothing
break;
case '(':
stack.push(i);
break;
case ')':
if(stack.isEmpty()){
System.out.println(")が多すぎます" + i);
return;
}
System.out.printf("%dと%dが対応%n", stack.pop(), i);
break;
}
}
if(!stack.isEmpty()){
System.out.println("(が多すぎます" + stack.pop());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment