LaiCode 395.Remove Certain Characters
题目
思路
- First we need to change the input string into a character array and put the string t into a Hashset.
- Then we need to set two pointers, slow and fast, to traverse the character array. The fast pointer will go through every element in each iteration and to see if the element exists in the set. If it exists in the set, then we set the value of the slow pointer’s elements the same as the fast pointer’s element. And move slow and fast pointer to their next element; If it doesn’t exiest in the set, then we only need to move the fast pointer to its next element and go for another iteration.
- When the fast pointer reach the end of the character array, the elements in front of the slow pointer is what we need, and we should construct a new string with these elements and return it.
代码实现
public class Solution {
public String remove(String input, String t) {
// Write your solution here
char[] inputStr = input.toCharArray();
Set<Character> set = buildSet(t);
int slow = 0;
for (int fast = 0; fast < inputStr.length; fast++) {
if (!set.contains(inputStr[fast])) {
inputStr[slow++] = inputStr[fast];
}
}
return new String(inputStr, 0, slow);
}
private Set<Character> buildSet(String t) {
Set<Character> set = new HashSet<>();
for (int i = 0; i < t.length(); i++) {
set.add(t.charAt(i));
}
return set;
}
}
复杂度分析
这种解法的时间复杂度是O(m + n),其中m代表t的长度,n代表input的长度。
空间复杂度是O(m + n),因为要额外创建一个hashset,大小等同于t的大小;还有一个char array,大小等同于input的长度。