- represent the entire alphebat as array and get y x by index/5 and index%5
- corner case of z: when we change one character to z, make sure ‘L’ first and 'D'
class Solution {
//corner case: z
public String alphabetBoardPath(String target) {
String str ="abcdefghijklmnopqrstuvwxyz";
StringBuilder sb = new StringBuilder();
int y = 0, x = 0;
for(int i= 0; i<target.length(); i++){
char c = target.charAt(i);
int index = str.indexOf(c);
int ty = index/5;
int tx = index%5;
//add uplr into sb
int yDiff = ty-y;
int xDiff = tx-x;
if(c=='z' && i!=0){
//5 0
//0 3
//System.out.println(ty+" "+tx);
//System.out.println("l"+i);
if(xDiff>0){
while(xDiff>0){
sb.append('R');
xDiff--;
}
}else{
xDiff = -xDiff;
while(xDiff>0){
sb.append('L');
xDiff--;
}
}
if(yDiff>0){
while(yDiff>0){
sb.append('D');
yDiff--;
}
}else{
yDiff = -yDiff;
while(yDiff>0){
sb.append('U');
yDiff--;
}
}
}else {
if(yDiff>0){
while(yDiff>0){
sb.append('D');
yDiff--;
}
}else{
yDiff = -yDiff;
while(yDiff>0){
sb.append('U');
yDiff--;
}
}
if(xDiff>0){
while(xDiff>0){
sb.append('R');
xDiff--;
}
}else{
xDiff = -xDiff;
while(xDiff>0){
sb.append('L');
xDiff--;
}
}
}
sb.append('!');
y =ty;
x = tx;
}
return sb.toString();
}
}
- move x and y, when x==4 && y>0 breaj since it hits z