最近写作业写到回文,用栈来判断,我是将字符串push后在pop,然后比较两个字符串是否相同,相同就是回文字符串,不同就不是。以下是我的代码,有些粗糙,希望能得到大家的指导。
package data;
/**
* 将str压入栈中,然后将栈中数据出栈,
* 比较s和str是否相同,
* 相同即回文,不同即非回文
*/
import java.util.*;
public class Circle {
public static void main(String[] args) throws Exception {
System.out.println("输入一段英文字符串:");
Scanner sc = new Scanner(System.in);
if(isCircle(sc.next()))
System.out.println("该字符串为回文字符");
else
System.out.println("该字符串不是回文字符");
}
public static boolean isCircle(String str) throws Exception {
int length = str.length();
Stack st = new Stack(length);
for(int i=0;i<length;i++) {
char c = str.charAt(i);
String t = String.valueOf(c);
st.push(t);
}
String s = "";
for(int i=0;i<length;i++) {
s=s+st.pop().toString();
}
if(s.equals(str))
return true;
else
return false;
}
}