diff --git a/leetcode/1901-2000/1910.Remove-All-Occurrences-of-a-Substring/Solution.go b/leetcode/1901-2000/1910.Remove-All-Occurrences-of-a-Substring/Solution.go index ce77c9053..8284a6984 100644 --- a/leetcode/1901-2000/1910.Remove-All-Occurrences-of-a-Substring/Solution.go +++ b/leetcode/1901-2000/1910.Remove-All-Occurrences-of-a-Substring/Solution.go @@ -19,3 +19,31 @@ func Solution(s string, part string) string { return s } + +func Solution1(s string, part string) string { + bs := []byte(s) + index := -1 + l := len(part) + lastByte := part[l-1] + for i := 0; i < len(s); i++ { + index++ + bs[index] = s[i] + if s[i] != lastByte { + continue + } + + if start := index - l + 1; start >= 0 { + if string(bs[start:index+1]) == part { + index = start - 1 + } + } + + } + if start := index - l + 1; start >= 0 { + if string(bs[start:index+1]) == part { + index = start - 1 + } + } + + return string(bs[:index+1]) +} diff --git a/leetcode/1901-2000/1910.Remove-All-Occurrences-of-a-Substring/Solution_test.go b/leetcode/1901-2000/1910.Remove-All-Occurrences-of-a-Substring/Solution_test.go index 6d7ff7dff..b572abe27 100644 --- a/leetcode/1901-2000/1910.Remove-All-Occurrences-of-a-Substring/Solution_test.go +++ b/leetcode/1901-2000/1910.Remove-All-Occurrences-of-a-Substring/Solution_test.go @@ -30,6 +30,30 @@ func TestSolution(t *testing.T) { } } +func TestSolution1(t *testing.T) { + // 测试用例 + cases := []struct { + name string + s, p string + expect string + }{ + {"TestCase1", "daabcbaabcbc", "abc", "dab"}, + {"TestCase2", "axxxxyyyyb", "xy", "ab"}, + {"TestCase3", "eemckxmckx", "emckx", ""}, + } + + // 开始测试 + for i, c := range cases { + t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) { + got := Solution1(c.s, c.p) + if !reflect.DeepEqual(got, c.expect) { + t.Fatalf("expected: %v, but got: %v, with inputs: %v %v", + c.expect, got, c.s, c.p) + } + }) + } +} + // 压力测试 func BenchmarkSolution(b *testing.B) { }