It took me about 20 minutes to think about the solution for this medium LC problem and just few minutes to actually implement the code.
The idea is straightforward: Create a mapping for each character in their corresponding coordingate. Then for each character of the target word, compute the difference in x and y axis. The magnitude of the difference becomes the multipler for the character that we’re going to append to the output. Also, the sign of the difference decides whether we should go up or down, left or right.
A special case for the character ‘z’ needs to be handled as well.
class Solution {
public String alphabetBoardPath(String target) {
final Map<Integer, int[]> mapping = new HashMap<>();
for(int i=0; i < 26; i++){
mapping.put(i, new int[]{i / 5, i % 5});
}
int[] prev = new int[]{0,0};
final StringBuilder builder = new StringBuilder();
for(int i=0; i < target.length(); i++){
if(i > 0 && target.charAt(i) == target.charAt(i - 1)){
builder.append('!');
continue;
}
int current = target.charAt(i) - 'a';
int[] tLoc = mapping.get(current);
int xDiff = tLoc[0] - prev[0];
int yDiff = tLoc[1] - prev[1];
if(current != 25){
char c = 'D';
if(xDiff < 0){
xDiff = xDiff * -1;
c = 'U';
}
while(xDiff-- > 0){
builder.append(c);
}
c = 'R';
if(yDiff < 0){
yDiff = yDiff * -1;
c = 'L';
}
while(yDiff-- > 0){
builder.append(c);
}
}else{
xDiff--;
while(xDiff-- > 0){
builder.append('D');
}
yDiff *= -1;
while(yDiff-- > 0){
builder.append('L');
}
builder.append('D');
}
builder.append("!");
prev = tLoc;
}
return builder.toString();
}
}
Runtime: 1 ms, faster than 52.35% of Java online submissions for Alphabet Board Path.
Memory Usage: 37.9 MB, less than 100.00% of Java online submissions for Alphabet Board Path.