字符串升序判断-java

package CodeCheck;

import java.util.Arrays;

// 26进制减法
public class CodeCheck{
    // 方法一:
    public boolean checkCodeIncrease(String s1, String s2) {
        // s1加1生成s3判断s2==s3 或者 s2-s1差值是否是1
        char[] chars1 = s1.toCharArray();
        int index = chars1.length-1;
        char[] chars3 = Arrays.copyOf(chars1, index+1);
        int carry = 0;
        int curCharNum = (int)chars1[index];


        // A:97 - Z:122
        while(index >=0) {
            if(curCharNum == 122) {
                chars3[index] = 'A';
                curCharNum = (int)chars1[index];
            } else {
                chars3[index] = (char)((int)chars1[index]+1);
                return new String(chars3).equals(s2);
            }
            index--;
        }
        // while结束还没退出,说明最后是全Z进位,头部追加一个A
        return "A".concat(new String(chars3)).equals(s2);
    }

    // 字符串转26进制数字,可能问题:字符过长容易超出数字最大边界
    public int str2Num(String str) {
        int res = 0;
        int multiple = 1;
        for(int i = str.length() - 1; i >= 0; i--) {
            int curNum = str.charAt(i) - 'A' + 1;
            res += curNum * multiple;
            multiple *= 26;
        }
        return res;
    }
    // 方法二:
    public boolean limitCheck(String s1, String s2) {
        return str2Num(s2) - str2Num(s1) == 1;
    }

    public  static void main(String[] args) {
//        CodeCheck checker = new CodeCheck();
//        boolean r1 = checker.limitCheck("ZZZZZZZZZZZZZZZ", "AAAAAAAAAAAAAAAA");
//        System.out.println("r1 : " + r1 );
        r1 = checker.limitCheck("AA", "AB");
        System.out.println("r1 : " + r1 );
    }
}

你可能感兴趣的:(字符串升序判断-java)