diff options
-rw-r--r-- | remove_substring.c | 8 | ||||
-rw-r--r-- | remove_substring.cpp | 29 | ||||
-rw-r--r-- | remove_substring.py | 27 |
3 files changed, 33 insertions, 31 deletions
diff --git a/remove_substring.c b/remove_substring.c index 7a7aa38..45c6fa3 100644 --- a/remove_substring.c +++ b/remove_substring.c @@ -1,7 +1,5 @@ // 1910. Remove All Occurrences of a Substring -#include <stdio.h> -#include <stdlib.h> -#include <string.h> +#include "leetcode.h" /* * given two strings 's' and 'part', perform the following operation on 's' @@ -24,8 +22,8 @@ char *removeOccurrences(char *s, char *part) { } int main() { - char s1[] = {"daabcbaabcbc"}, p1[] = {"abc"}; - char s2[] = {"axxxxyyyyb"}, p2[] = {"xy"}; + char *s1 = "daabcbaabcbc", *p1 = "abc"; + char *s2 = "axxxxyyyyb", *p2 = "xy"; printf("%s\n", removeOccurrences(s1, p1)); // expect: dab printf("%s\n", removeOccurrences(s2, p2)); // expect: ab } diff --git a/remove_substring.cpp b/remove_substring.cpp index f3744ab..a5572be 100644 --- a/remove_substring.cpp +++ b/remove_substring.cpp @@ -10,34 +10,11 @@ */ class Solution { - bool check(stack<char> stk, string part) { - int n = part.size(), j = n - 1; - while (j >= 0 && stk.top() == part[j]) - stk.pop(), j--; - return j == -1; - } - public: string removeOccurrences(string s, string part) { - int n1 = s.size(), n2 = part.size(); - stack<char> stk; - string str = ""; - for (int i = 0; i < n1; i++) { - stk.push(s[i]); - if (stk.size() >= n2) - if (check(stk, part)) { - int cnt = n2; - while (cnt--) - stk.pop(); - } - } - string ans = ""; - while (!stk.empty()) { - ans += stk.top(); - stk.pop(); - } - reverse(ans.begin(), ans.end()); - return ans; + while (s.size() && s.find(part) < s.size()) + s.erase(s.find(part), part.size()); + return s; } }; diff --git a/remove_substring.py b/remove_substring.py new file mode 100644 index 0000000..d273606 --- /dev/null +++ b/remove_substring.py @@ -0,0 +1,27 @@ +# 1910. Remove All Occurrences of a Substring + +""" +given two strings 's' and 'part', perform the following operation on 's' +until all occurrences of the substring 'part' are removed; find the leftmost +occurrence of the substring 'part' and remove it from 's'. return 's' after +removing all occurrences of 'part'. a substring is a contiguous sequence of +characters in a string +""" + + +class Solution(object): + def removeOccurrences(self, s, part): + """ + :type s: str + :type part: str + :rtype: str + """ + while part in s: + s = s.replace(part, "", 1) + return s + + +if __name__ == "__main__": + obj = Solution() + print(obj.removeOccurrences(s="daabcbaabcbc", part="abc")) + print(obj.removeOccurrences(s="axxxxyyyyb", part="xy")) |