package easy;
import java.util.Arrays;
import java.util.List;
public class LC_20_isValid {
public static byte getIndex(char c) {
switch (c) {
case '(':return 0;
case '[':return 1;
case '{':return 2;
case ')':return 3;
case ']':return 4;
case '}':return 5;
default:break;
}
return 0;
}
public static boolean isValid(String s) {
byte[] stack=new byte[s.length()+10];
int top=-1;
byte j=0;
for (int i=0;i<s.length();i++)
{
j=getIndex(s.charAt(i));
if (j<3) {
stack[++top]=j;
continue;
}
if (j>=3 && top<0) return false;
if (j-stack[top]==3)
top--;
else
return false;
}
return top==-1;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
List<String> inputs=Arrays.asList("()","()[]{}","([","([)]","{[]}");
for (String input :inputs)
System.out.println(LC_20_isValid.isValid(input));
}
}
这道题当时战胜了99.28%的java提交,哈哈,很开心