日期:2014-05-20 浏览次数:21177 次
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Excel
{
    final char[] COL =
    { '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' };
    public static void main(String[] args)
    {
    Scanner sc = new Scanner(System.in);
    int count = sc.nextInt();
    if (count <= 0 || count > 100)
    {
        System.out.println("次数超出限制");
        return;
    }
    ArrayList<String> ar = new ArrayList<String>();
    while (count > 0)
    {
        String command = sc.next();
        ar.add(command);
        count--;
    }
    for (String command : ar)
    {
        Excel e = new Excel();
        e.convert(command.trim().toUpperCase());
    }
    }
    public void convert(String address)
    {
    String regex = "[A-Z]+[0-9]*";
    Pattern pt = Pattern.compile(regex);
    Matcher mather = pt.matcher(address);
    ArrayList<String> ar = new ArrayList<String>();
    while (mather.find())
    {
        String s = mather.group();
        ar.add(s);
    }
    if (ar.size() > 0)
    {
        String row = ar.get(0);
        String col = ar.get(1);
        int rowNum = Integer.parseInt(row.substring(1));
        int colNum = Integer.parseInt(col.substring(1));
        String newCol = "";
        newCol += COL[colNum % 26 - 1];
        while (colNum / 26 > 0)
        {
        colNum /= 26;
        newCol += COL[colNum % 26 - 1];
        }
        String buffer = "";
        for (int i = newCol.length() - 1; i >= 0; i--)
        {
        buffer += newCol.charAt(i);
        }
        System.out.println(buffer + rowNum);
    }
    }
}
------解决方案--------------------
    // From R5C255 to IU5 - 第5行第255列
    public static String transRC(String rc)
    {
        Pattern p = Pattern.compile("[0-9]+");
        Matcher m = p.matcher(rc);
        int line = 0;
        int row = 0;
        if (m.find())
            line = Integer.parseInt(m.group(0));
        if (m.find())
            row = Integer.parseInt(m.group(0));
        System.out.println("LINE: " + line + " ROW: " + row);
        return transCol(row) + line;
    }
    private static String transCol(int row)
    {
        if (row < 1 || row > 26 * 26)
        {
            return null;
        }
        else if (row <= 26)
        {
            return "" + (char) (row + 'A' - 1);
        }
        else
        {
            return "" + (char) (((row - row % 26) / 26) + 'A' - 1)
                    + (char) ((row % 26) + 'A' - 1);
        }
    }