题目地址:
https://www.lintcode.com/problem/character-deletion/description
给定两个字符串 s s s和 t t t,要求将 s s s中把 t t t所含的字符都删掉。返回剩余字符组成的字符串。
代码如下:
import java.util.HashSet;
import java.util.Set;
public class Solution {
/**
* @param str: The first string given
* @param sub: The given second string
* @return: Returns the deleted string
*/
public String CharacterDeletion(String str, String sub) {
// write your code here
Set<Character> set = new HashSet<>();
for (int i = 0; i < sub.length(); i++) {
set.add(sub.charAt(i));
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (set.contains(ch)) {
continue;
}
sb.append(ch);
}
return sb.toString();
}
}
时间复杂度 O ( l s + l t ) O(l_s+l_t) O(ls+lt),空间 O ( l t ) O(l_t) O(lt)。