1 回答

TA貢獻1827條經驗 獲得超8個贊
我不太明白你試圖確定分離的部分。在 Go 中,就像在 C 中一樣,您可以對字符進行算術運算。例如,您將獲得每個小寫字母的從 0 開始的索引:
pos := char - 'a';
你可以"abxyz"
轉向
{0, 1, 23, 24, 25}.
如果你計算相鄰字母之間的差異,你會得到
{-25, 1, 22, 1, 1}
(-25 是最后一個值和第一個值之間的差值。)有兩個間隙:一個間隙是循環在 b 和 w 之間開始的間隙,另一個間隙是字母表換行的間隙。第二個間隙是差值為負的地方,總是在最后一項和第一項之間。您可以在差值上加上 26 來調整它,也可以使用模算術,其中使用余數%
來計算環繞:
diff := ((p - q + 26) % 26;
如果第一個操作數為正,則強制%
結果范圍為 0 到 25。+ 26 強制其為正數。(下面的程序使用 25,因為您對分隔的定義不是位置的差異,而是兩者之間的過濾器數量。)
現在你已經看到了差異
{1, 1, 22, 1, 1}
當最多只有兩個不同的值并且其中一個最多出現一次時,就滿足您的條件。(我發現這個條件測試起來非常復雜,見下文,但部分原因是 Go 的映射有點麻煩。)
無論如何,這是代碼:
package main
import "fmt"
func list(str string) int {
present := [26]bool{}
pos := []int{}
count := map[int]int{}
// determine which letters exist
for _, c := range str {
if 'a' <= c && c <= 'z' {
present[c-'a'] = true
}
}
// concatenate all used letters (count sort, kinda)
for i := 0; i < 26; i++ {
if present[i] {
pos = append(pos, i)
}
}
// find differences
q := pos[len(pos)-1]
for _, p := range pos {
diff := (p - q + 25) % 26
count[diff]++
q = p
}
// check whether input is a "rambai"
if len(count) > 2 {
return -1
}
which := []int{}
occur := []int{}
for k, v := range count {
which = append(which, k)
occur = append(occur, v)
}
if len(which) < 2 {
return which[0]
}
if occur[0] != 1 && occur[1] != 1 {
return -1
}
if occur[0] == 1 {
return which[1]
}
return which[0]
}
func testme(str string) {
fmt.Printf("\"%s\": %d\n", str, list(str))
}
func main() {
testme("zzzzyyyybbbzzzaaaaaxxx")
testme("yacegw")
testme("keebeebheeh")
testme("aco")
testme("naan")
testme("mississippi")
testme("rosemary")
}
package main
import "fmt"
func list(str string) int {
present := [26]bool{}
pos := []int{}
count := map[int]int{}
// determine which letters exist
for _, c := range str {
if 'a' <= c && c <= 'z' {
present[c-'a'] = true
}
}
// concatenate all used letters (count sort, kinda)
for i := 0; i < 26; i++ {
if present[i] {
pos = append(pos, i)
}
}
// find differences
q := pos[len(pos)-1]
for _, p := range pos {
diff := (p - q + 25) % 26
count[diff]++
q = p
}
// check whether input is a "rambai"
if len(count) > 2 {
return -1
}
which := []int{}
occur := []int{}
for k, v := range count {
which = append(which, k)
occur = append(occur, v)
}
if len(which) < 2 {
return which[0]
}
if occur[0] != 1 && occur[1] != 1 {
return -1
}
if occur[0] == 1 {
return which[1]
}
return which[0]
}
func testme(str string) {
fmt.Printf("\"%s\": %d\n", str, list(str))
}
func main() {
testme("zzzzyyyybbbzzzaaaaaxxx")
testme("yacegw")
testme("keebeebheeh")
testme("aco")
testme("naan")
testme("mississippi")
testme("rosemary")
}
https://play.golang.org/p/ERhLxC_zfjl
- 1 回答
- 0 關注
- 199 瀏覽
添加回答
舉報