Skip to content

Instantly share code, notes, and snippets.

@kishida
Created January 22, 2016 16:59
Show Gist options
  • Save kishida/fa07499ab128d9e8633b to your computer and use it in GitHub Desktop.
Save kishida/fa07499ab128d9e8633b to your computer and use it in GitHub Desktop.
Retrieve a pair of parenthesis with recursion.
package javaapplication1.beginer;
/**
*
* @author naoki
*/
public class AaaParenthesisRecursion {
public static void main(String[] args) {
String aaa = "aaa(aaa(aa((aaa)aa))aa)a";
for(int i = 0; i < aaa.length(); ++i){
char ch = aaa.charAt(i);
switch(ch){
case 'a':
break; // do nothing
case ')':
System.out.println(")が多すぎます" + i);
return;
case '(':
i = inParenthesis(aaa, i);
break;
}
}
}
private static int inParenthesis(String aaa, int start) {
for(int i = start + 1; i < aaa.length(); ++i){
char ch = aaa.charAt(i);
switch(ch){
case 'a':
break; // do nothing
case ')':
System.out.printf("%dと%dが対応%n", start, i);
return i;
case '(':
i = inParenthesis(aaa, i);
break;
}
}
System.out.println("(が多すぎます" + start);
return aaa.length();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment