解密回文——栈
一、栈的概念
队列是一种先进先出的数据结构,而栈是后进先出的数据结构。栈限定为只能在一端进行插入和删除操作。
栈的实现:只需要一个一维数组和一个指向栈顶的变量top。通过top 来对栈进行插入和删除操作。
入栈:top++; s[top]=x; 可简写为s[++top]=x;
二、代码实现
【问题1】
描述:判断一个字符串是否为回文。
输入:
ahaha
输出:
YES
代码:
1 import java.util.Scanner; 2 3 public class Main { 4 public static void main(String[] args) { 5 // TODO Auto-generated method stub 6 Scanner reader = new Scanner(System.in); 7 String s = reader.next(); 8 int mid=s.length()/2-1; 9 char s1[] = new char[mid+1]; 10 //左边的字符入栈 11 int top=0; 12 for(int i=0;i<=mid;i++){ 13 s1[i]=s.charAt(i); 14 top++; 15 } 16 17 //判断字符串长度为奇数or偶数 18 int next; 19 if(s.length()%2==0) 20 next=mid+1; 21 else next=mid+2; 22 23 //匹配 24 for(int i=next;i<s.length();i++){ 25 if(s.charAt(i)!=s1[top]) 26 break; 27 top--; 28 } 29 if(top==0) 30 System.out.println("YES"); 31 else System.out.println("NO"); 32 } 33 }
【问题2】
描述:进行验证括号的匹配。比如输入一行只包含“()[]{}”的字符串,请判断形如“([{}()])”或者“{()[]{}}”的是否可以正确匹配。显然上面两个例子都是可以正确匹配的。“([)]”是不能匹配的。
输入:
([{}()])
输出:
YES
代码:
1 import java.util.Scanner; 2 3 public class Main { 4 public static void main(String[] args) { 5 // TODO Auto-generated method stub 6 Scanner reader = new Scanner(System.in); 7 String s = reader.next(); 8 char c[] = new char[s.length()]; 9 10 int top=0; 11 for(int i=0;i<s.length();i++){ 12 //入栈 13 c[top]=s.charAt(i); 14 top++; 15 //将栈内元素进行匹配,若栈顶两个元素匹配,则一起出栈 16 if(top>1){ 17 if(c[top-1]=='}'){ 18 if(c[top-2]=='{') 19 top=top-2; 20 } 21 else if(c[top-1]==']'){ 22 if(c[top-2]=='[') 23 top=top-2; 24 } 25 else if(c[top-1]==')'){ 26 if(c[top-2]=='(') 27 top=top-2; 28 } 29 } 30 } 31 32 if(top==0) 33 System.out.println("YES"); 34 else System.out.println("NO"); 35 } 36 }