我有一个算法,但没有解决。我该如何解决?

时间:2018-07-14 18:03:13

标签: java string algorithm integer

public class Tester {
    static List<String> columnNames(int n) {

        List<String> result = new ArrayList<String>();
        String alphabets[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
        StringBuilder sb = new StringBuilder();
        for(int j = 0; j < n; j++){
            int index = j/26;
            char ch = (char) (j % 26 + 'A');
            sb.append(ch);
            String item = "";
            if(index > 0) {
                item += alphabets[index-1];
            }
            item += alphabets[j % 26];
            result.add(item);
        }
        sb.reverse();
        return result;
    }

我使用此功能,似乎可以,但是我给703输入(702可以,但703不能),我得到一个错误

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 26
    at example.Tester.columnNames(Tester.java:20)
    at example.Tester.main(Tester.java:34)

请帮助我。如果输入703必须为A,B,....... AA,AB,....,ZZ,AAA,AAB,AAC ...

1 个答案:

答案 0 :(得分:1)

此行的外观在此行

colName = (position == 0 ? 'Z' : colName.charAt(position > 0 ? position - 1 : 0)) + colName;

因为ypu尝试从空字符串中获取colName.charAt(12)(如果输入等于13)。

如果要获取此输出(A,B,C,D,E,F,G,H,I,J,K,L,M),请尝试以下操作:

public class Test {
  static String columnNames(int n) {
    String capitalAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    return capitalAlphabet.substring(0, n);

  }

  public static void main(String[] args) throws IOException {
    Scanner in = new Scanner(System.in);
    System.out.println("sayi giriniz..");
    Integer input = in.nextInt();

    String result = columnNames(input);
    System.out.println(String.join(", ", result.split("")));
  }

}

输入

13

输出

A, B, C, D, E, F, G, H, I, J, K, L, M