面试老是会遇到一些用String来考算法的题目,要取出String里的每一个字符然后处理,比如下面这种:判断下面的字符串是否对称:a,aa,aba.
今天就写了一个简单的String迭代,支持顺序,倒序处理,调用stringNext拿到每一个位置上的字符.
代码如下:
public class StringOrder {
private String s;
private boolean order = true;
private char stringCur;
public char getStringCur() {
return stringCur;
}
public int getLoc() {
return loc;
}
private int loc;
public StringOrder(String s){
this.s = s;
}
public StringOrder(String s, boolean order){
this.s = s;
this.order = order;
if(!order){
loc = s.length();
}
}
public String stringNext(){
if(!order){
if(loc == 0){
return null;
}
loc--;
stringCur = s.charAt(loc);
}else{
if(loc == s.length()){
return null;
}
stringCur = s.charAt(loc);
loc++;
}
return stringCur+"";
}
}
利用这个解决上面的问题,代码如下:
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
String a = "987t123aad1daa321t789";
System.out.println(new Test().judgePairString(a));
new Test().printPairString(a);
}
public boolean judgePairString(String s){
StringOrder o1 = new StringOrder(s,true);
StringOrder o2 = new StringOrder(s,false);
for(int i=0;i<s.length();i++){
if(!o1.stringNext().equals(o2.stringNext())){
return false;
}
}
return true;
}
public void printPairString(String s){
if(judgePairString(s)){
for(int i=0;i<s.length()/2;i++){
System.out.println("PairString[" + i + "]:" + s.charAt(i));
}
}else{
System.out.println("[" + s + "] is not a PairString");
}
}
}