算法:回文字符串的判断

“回文”是指正读反读都能读通的句子,即正反数字的顺序都是一样的,比如:12321,回文字符串如:abcdfdcba。并不是所有的字符串都拥有回文功能。现给出一个字符串,判断是否拥有回文功能,如是返回true,否则返回not possible。其中可允许去掉1~2个字段,再判断即可。比如:

abcrtcba:去掉cr后同样返回'rt',表示为回文字符串,同时提示去掉rt后的回文字符串
321t123:去掉t后返回't',表示为回文字符串,同时提示去掉t后的回文字符串
rttr:不返回任何数据,直接返回true,
wiouiow:返回false

上代码


public  class StringPalindrome {


    public static String StringChallenge(String str) {
        // code goes here
        if (str==null || str.trim().length()==0){
           return "";
        }

        for(int n=0;n<=2;n++){
            String str1= "";
            String removeStr = "";
            if (n>0 && str.length()>n){
                removeStr= str.substring(0,n);
                str1 = str.substring(n);
            }else{
                str1 = str;
            }

            String str2 = "";
            char[] ch = str1.toCharArray();
            for(int i=ch.length-1;i>=0;i--){
                str2+=ch[i];
            }
            if (str1.equals(str2)){
                System.out.print(removeStr);
                return removeStr;
            }
        }
        System.out.println(str + "not possible");
        return "";
    }

    public static void main (String[] args) {
        // keep this function call here
        Scanner s = new Scanner(System.in);
        StringChallenge(s.nextLine());
        //System.out.print(StringChallenge(s.nextLine()));
    }

}

你可能感兴趣的:(算法:回文字符串的判断)