Skip to content

Instantly share code, notes, and snippets.

@zhangguanzhang
Last active May 17, 2020 11:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhangguanzhang/791c484f6137f8deaed473a3857219ee to your computer and use it in GitHub Desktop.
Save zhangguanzhang/791c484f6137f8deaed473a3857219ee to your computer and use it in GitHub Desktop.
golang Remove the specified repeated string
package main
import (
"fmt"
)
func main() {
s := `aaabccaad`
u := "a"
fmt.Printf("%s %s ===> %s \n", s, u, uniq(s, u))
s = `hvafdaavhhaav`
fmt.Printf("%s %s ===> %s \n", s, u, uniq(s, u))
u = "h"
fmt.Printf("%s %s ===> %s \n", s, u, uniq(s, u))
}
func uniq(s string, uniq string) string {
var (
old uint8
count int
result string
)
for i := 0; i < len(s); i++ {
if string(s[i]) == uniq {
count++
if count == 1 && old != 0 {
result += string(old)
}
} else {
if count == 0 && old != 0 {
result += string(old)
}
if count > 0 {
result += string(old)
count = 0
}
}
old = s[i]
}
result += string(old)
return result
}
@zhangguanzhang
Copy link
Author

vvaaabccaad

v,  i: 0 , count: 0  result:                      , old:
v,  i: 1 , count: 0  result: v                    , old:v
a,  i: 2 , count: 1  result: vv                   , old:v
a,  i: 3 , count: 2  result: vv                   , old:a
a,  i: 4 , count: 3  result: vv                   , old:a
b,  i: 5 , count: 0  result: vva                  , old:b
c,  i: 6 , count: 0  result: vvab                 , old:c
c,  i: 7 , count: 0  result: vvabc                , old:c
a,  i: 8 , count: 1  result: vvabcc               , old:a
a,  i: 9 , count: 2  result: vvabcc               , old:a
d,  i: 10, count: 0  result: vvabcca              , old:d

@zhangguanzhang
Copy link
Author

func uniqx(s string, uniq string) string {
	var (
		ans  string
		flag bool
	)
	flag = false
	for _, cur := range s {
		// 如果上一个是相同的,而且当前还是 uniq
		if flag == true && string(cur) == uniq {
			continue
		}
		// 判断是否一样
		if string(cur) != uniq {
			flag = false
		} else if string(cur) == uniq {
			flag = true
		}
		ans += string(cur)
	}
	return ans
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment