1138. 字母板上的路径
1.想法
从a出发到任意的点例如 l,最直接的就是先走竖行再走横行
有一个特殊情况是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(startXc){
for(int j=0;j