76 lines
1.8 KiB
Java
76 lines
1.8 KiB
Java
/*
|
|
* @lc app=leetcode id=1138 lang=java
|
|
*
|
|
* [1138] Alphabet Board Path
|
|
*/
|
|
|
|
// @lc code=start
|
|
class Solution {
|
|
public String alphabetBoardPath(String target) {
|
|
char cur = 'a';
|
|
StringBuilder bd = new StringBuilder();
|
|
for(int i = 0; i < target.length(); i++) {
|
|
bd.append(actions(cur, target.charAt(i)));
|
|
cur = target.charAt(i);
|
|
}
|
|
return bd.toString();
|
|
}
|
|
|
|
private int[] distance(char a, char b) {
|
|
int[] pa = new int[] {
|
|
(a-'a') / 5,
|
|
(a-'a') % 5
|
|
};
|
|
int[] pb = new int[] {
|
|
(b - 'a') / 5,
|
|
(b - 'a') % 5
|
|
};
|
|
return new int[] {
|
|
pb[0] - pa[0],
|
|
pb[1] - pa[1]
|
|
};
|
|
}
|
|
|
|
private String actions(char s, char d) {
|
|
int[] move = distance(s, d);
|
|
StringBuilder builder = new StringBuilder();
|
|
if(move[0] == 0 && move[1] == 0) {
|
|
builder.append('!');
|
|
} else {
|
|
if(s == 'z') {
|
|
builder.append(rowActions(move[0]));
|
|
builder.append(colActions(move[1]));
|
|
} else {
|
|
builder.append(colActions(move[1]));
|
|
builder.append(rowActions(move[0]));
|
|
}
|
|
builder.append('!');
|
|
}
|
|
return builder.toString();
|
|
}
|
|
|
|
private String rowActions(int x) {
|
|
if(x == 0) {
|
|
return "";
|
|
}
|
|
return x > 0 ? repeatChar('D', x):repeatChar('U', -x);
|
|
}
|
|
|
|
private String colActions(int x) {
|
|
if(x == 0) {
|
|
return "";
|
|
}
|
|
return x > 0 ? repeatChar('R', x):repeatChar('L', -x);
|
|
}
|
|
|
|
private String repeatChar(char ch, int n) {
|
|
StringBuilder s = new StringBuilder();
|
|
for(int i = 0; i<n; i++) {
|
|
s.append(ch);
|
|
}
|
|
return s.toString();
|
|
}
|
|
}
|
|
// @lc code=end
|
|
|