Untitled
unknown
c_cpp
a year ago
955 B
7
Indexable
#include <string>
#include <vector>
#include <cmath>
int getDistance(string word) {
// Define the keyboard layout
vector<string> keyboard = {
"QWERTYUIOP",
"ASDFGHJKL",
"ZXCVBNM"
};
// Function to find coordinates of a letter
auto findCoords = [&](char c) -> pair<int, int> {
for (int i = 0; i < keyboard.size(); i++) {
int pos = keyboard[i].find(c);
if (pos != string::npos) {
return {i, pos};
}
}
return {-1, -1}; // Should never happen with valid input
};
int totalDistance = 0;
pair<int, int> currentPos = findCoords('Q'); // Start at Q
for (char c : word) {
pair<int, int> targetPos = findCoords(c);
totalDistance += abs(targetPos.first - currentPos.first) +
abs(targetPos.second - currentPos.second);
currentPos = targetPos;
}
return totalDistance;
}Editor is loading...
Leave a Comment