LeetCode 1165: Single-Row Keyboard Solution
Master LeetCode problem 1165 (Single-Row Keyboard), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1165. Single-Row Keyboard
Problem Explanation
Explanation:
To solve this problem, we need to find the time taken to type a given string using a single-row keyboard. The keyboard layout is given as a string of unique characters representing the keys in order. We iterate through the given word and calculate the time taken to type each character based on its position in the keyboard layout.
- Create a hashmap to store the index of each character in the keyboard layout.
- Initialize the total time taken to type as 0.
- Iterate through the characters in the given word.
- Calculate the time taken to type each character based on the absolute difference in indices between the current character and the previous character.
- Add this time to the total time taken.
- Return the total time taken to type the entire word. :
Solution Code
class Solution {
public int calculateTime(String keyboard, String word) {
Map<Character, Integer> keyboardMap = new HashMap<>();
for (int i = 0; i < keyboard.length(); i++) {
keyboardMap.put(keyboard.charAt(i), i);
}
int totalTime = 0;
int prevIndex = 0;
for (char c : word.toCharArray()) {
int currentIndex = keyboardMap.get(c);
totalTime += Math.abs(currentIndex - prevIndex);
prevIndex = currentIndex;
}
return totalTime;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1165 (Single-Row Keyboard)?
This page provides optimized solutions for LeetCode problem 1165 (Single-Row Keyboard) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1165 (Single-Row Keyboard)?
The time complexity for LeetCode 1165 (Single-Row Keyboard) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1165 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1165 in Java, C++, or Python.