Leetcode 2810. Faulty Keyboard
Imagine you are using a keyboard that is faulty. The only type of input it accepts correctly are alphabetical characters. However, for every character it prints, it erroneously includes a duplicate character immediately next to it. Thus, if you input the string “leetcode”, it will print “lleettccooddee”.
Given a string s
generated by such a faulty keyboard, your task is to reconstruct the original string that you meant to type.
s
?
s.length()
up to (10^5).s
only consist of lowercase alphabetical characters here?
s
only consists of lowercase a-z characters.The faulty keyboard prints each character twice consecutively. Thus, the solution needs to iterate over the input string, picking every second character to reconstruct the original string.
Here’s the Java code to solve the problem:
public class FaultyKeyboard {
public static String fixFaultyKeyboard(String s) {
StringBuilder originalString = new StringBuilder();
// Iterate over the input string, taking every second character
for (int i = 0; i < s.length(); i += 2) {
originalString.append(s.charAt(i));
}
return originalString.toString();
}
public static void main(String[] args) {
String inputString = "lleettccooddee";
System.out.println(fixFaultyKeyboard(inputString)); // Output: leetcode
}
}
The time complexity for this solution is (O(n)), where (n) is the length of the input string s
. This is because we are simply iterating through the string once.
StringBuilder
allows us to efficiently build the result string.i
by 2 in each iteration, we only append the first of every pair of characters to the StringBuilder
.StringBuilder
to a string and return it as the result.For an input of s = "lleettccooddee"
, the output will be "leetcode"
because we take the first of every adjacent pair:
Thus, the reconstructed original string is "leetcode"
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?