Last active
January 22, 2016 16:59
-
-
Save kishida/149c20f82530fb5a38b1 to your computer and use it in GitHub Desktop.
Retrieve a pair of parenthesis with Stack.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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