my
class tt1
{
public static void main(String[] args)
{
String s ="(]";
System.out.println(isValid(s));
}
public static boolean isValid(String s)
{
int youbiao = 0;
int shu = 0;
for (int i =0; i<s.length(); i++ )
{
youbiao = getyou(s.charAt(i),s);
System.out.println("i="+i);
System.out.println("youbiao="+youbiao);
if (((youbiao-i) % 2 == 0) )
{
return false;
}
/*
shu = shu++;
if (shu>s.length()/2)
{
}
*/
}
return true;
}
public static int getyou(char zuo,String s)
{
char[] init = {'(',')','{','}','[',']'};
int j = 0;
for (int m = 0; m < init.length ;m = m + 2 )
{
if (zuo == init[m])
{
j = 0;
while(j<s.length())
{
if (s.charAt(j) == init[m+1])
{
break;
}
j++;
}
}
else if (zuo == init[m+1])
{
//要将j++放在后面,否则会出界,也访问不到s[0]
j = 0;
while(j<s.length())
{
if (s.charAt(j) == init[m])
{
break;
}
j++;
}
}
}
/*
if (zuo = '(')
{
while(j<s.length())
{
j++;
if (s.charAt(j) == ')')
{
break;
}
}
}
*/
return j;
}
}
参考: HashMap结合Stack
class Solution {
public boolean isValid(String s) {
int n = s.length();
if (n % 2 == 1) {
return false;
}
Map<Character, Character> pairs = new HashMap<Character, Character>() {{
put(')', '(');
put(']', '[');
put('}', '{');
}};
Deque<Character> stack = new LinkedList<Character>();
for (int i = 0; i < n; i++) {
char ch = s.charAt(i);
//如果是右边的括号;第一个就是右括号,或者右括号与进栈的括号不匹配,则错误,如果匹配,则出栈
if (pairs.containsKey(ch)) {
if (stack.isEmpty() || stack.peek() != pairs.get(ch)) {
return false;
}
stack.pop();
}
//栈是先进后出,先判断最近的括号是否匹配
else {
stack.push(ch);
}
}
return stack.isEmpty();
}
}