1138. 字母板上的路径

2019-08-12  本文已影响0人  最困惑的时候就是能成长的时候

1138. 字母板上的路径

1.想法

image.png

从a出发到任意的点例如 l,最直接的就是先走竖行再走横行


image.png

有一个特殊情况是Z,只能向上走

所以,我们的步骤是.先得到当前的位置信息,和要去的位置信息,最后进行移动

2:代码

class Solution {
    public String alphabetBoardPath(String target) {
        StringBuilder sb = new StringBuilder();
         char[][] board = new char[6][5];
         board[0] = new char[]{'a','b','c','d','e'};
         board[1] = new char[]{'f','g','h','i','j'};
         board[2] = new char[]{'k','l','m','n','o'};
         board[3] = new char[]{'p','q','r','s','t'};
         board[4] = new char[]{'u','v','w','x','y'};
         board[5] = new char[]{'z','0','0','0','0'};
         //字母板
         char[] chars = target.toCharArray();
         int startX=0,startY=0;
         char nowCh ='a';
         for(char c:chars){
             if(nowCh == c){  //如果当前的字母和上一个相同,直接添加!
                 sb.append("!");
             }else {
                 int[] pos = getMyCharPos(board, c);  //先得到位置
                 sb.append(getMyOrder(startX, startY, pos[0], pos[1]));//添加移动指令
                 startX = pos[0];  //移动到指令位置
                 startY = pos[1];
             }
             nowCh = c; //更新该char
         }
         return sb.toString();
    }

    private String getMyOrder(int startX, int startY, int endX, int endY) {
        StringBuilder sb = new StringBuilder();
        boolean flag = false;
        if(startX ==5&&startY == 0){
            sb.append("U");
            startX--;
        }
        if(endX == 5&&endY==0){
            endX--;
            flag = true;
        }
        //处理X
        if(startX<endX){
            while(endX!=startX){
                sb.append("D");
                startX++;
            }
        }else{
            while(endX!=startX){
                sb.append("U");
                startX--;
            }
        }
        //处理Y
        if(startY<endY){
            while(endY!=startY){
                sb.append("R");
                startY++;
            }
        }else{
            while(endY!=startY){
                sb.append("L");
                startY--;
            }
        }
        if(flag){
            sb.append("D");
        }
        sb.append("!");
        return sb.toString();
    }

    private int[] getMyCharPos(char[][] board, char c) {
        int[] pos = new int[2];
        for(int i=0;i<board.length;i++){
            if(board[i][0] == c){
                pos[0] = i;
                pos[1] = 0;
                break;
            }
            if(board[i][0] <c&&board[i+1][0]>c){
                for(int j=0;j<board[i].length;j++){
                    if(board[i][j] == c){
                        pos[0] = i;
                        pos[1] = j;
                    }
                }
            }
        }
        return pos;
    }
}
上一篇下一篇

猜你喜欢

热点阅读