Remove Character
Problem​
Given two strings string1 and string2, remove those characters from first string(string1) which are present in second string(string2). Both the strings are different and contain only lowercase characters.
NOTE: Size of first string is always greater than the size of second string( |string1| > |string2|).
Examples:​
Example 1:
Input:
string1 = "computer"
string2 = "cat"
Output: "ompuer"
Explanation: After removing characters(c, a, t) from string1 we get "ompuer".
Example 2:
Input:
string1 = "occurrence"
string2 = "car"
Output: "ouene"
Explanation: After removing characters (c, a, r) from string1 we get "ouene".
Your task:​
You dont need to read input or print anything. Complete the function removeChars() which takes string1 and string2 as input parameter and returns the result string after removing characters from string2 from string1.
- Expected Time Complexity:
- Expected Auxiliary Space:
Constraints:​
Solution​
Python​
def removeChars (ob, string1, string2):
set_string2 = set(string2)
result = []
for char in string1:
if char not in set_string2:
result.append(char)
return ''.join(result)
Java​
static String removeChars(String string1, String string2){
Set<Character> setString2 = new HashSet<>();
for (char c : string2.toCharArray()) {
setString2.add(c);
}
StringBuilder result = new StringBuilder();
for (char c : string1.toCharArray()) {
if (!setString2.contains(c)) {
result.append(c);
}
}
return result.toString();
}
C++​
string removeChars(string string1, string string2) {
unordered_set<char> setString2;
for (char c : string2) {
setString2.insert(c);
}
string result;
for (char c : string1) {
if (setString2.find(c) == setString2.end()) {
result += c;
}
}
return result;
}
C​
void removeChars(char *string1, char *string2) {
int map[256] = {0};
for (int i = 0; i < strlen(string2); ++i) {
map[(int)string2[i]] = 1;
}
int index = 0;
for (int i = 0; i < strlen(string1); ++i) {
if (!map[(int)string1[i]]) {
string1[index++] = string1[i];
}
}
string1[index] = '\0';
}
- Time Complexity:
- Auxiliary Space: