From ec33de1b1ee5f4a4bfdd4fee82654745e18d4572 Mon Sep 17 00:00:00 2001 From: lazywhite <346816483@qq.com> Date: Thu, 23 Jun 2022 21:29:51 +0800 Subject: [PATCH] update --- "005.\344\271\260\346\261\275\346\260\264.go" | 43 +++++++++++++++++++ ...55\347\232\204\345\215\225\350\257\215.go" | 41 +++++++++++------- 2 files changed, 68 insertions(+), 16 deletions(-) create mode 100644 "005.\344\271\260\346\261\275\346\260\264.go" diff --git "a/005.\344\271\260\346\261\275\346\260\264.go" "b/005.\344\271\260\346\261\275\346\260\264.go" new file mode 100644 index 0000000..18b1230 --- /dev/null +++ "b/005.\344\271\260\346\261\275\346\260\264.go" @@ -0,0 +1,43 @@ +/* + +每瓶汽水单价2元 +规则 + 4个瓶盖可以换1瓶汽水 + 2个空瓶可以换1瓶汽水 + +30元可以喝到多少瓶汽水? +*/ + +package main + +import "fmt" + +func main() { + fmt.Println(countBottle(30)) +} + +func countBottle(n int) int { + unitPrice := 2 + + lid := n / unitPrice + empty := n / unitPrice + total := n / unitPrice + + newBottle := 0 // 兑换到的新瓶子 + + // 注意准入条件 + for lid+newBottle >= 4 || empty+newBottle >= 2 { + // 1. drink + lid += newBottle + empty += newBottle + + // 2. 兑换 + newBottle = lid/4 + empty/2 + total += newBottle + + lid %= 4 + empty %= 2 + } + + return total +} diff --git "a/151.\351\242\240\345\200\222\345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\215\225\350\257\215.go" "b/151.\351\242\240\345\200\222\345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\215\225\350\257\215.go" index 72e376f..611ab6b 100644 --- "a/151.\351\242\240\345\200\222\345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\215\225\350\257\215.go" +++ "b/151.\351\242\240\345\200\222\345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\215\225\350\257\215.go" @@ -66,33 +66,42 @@ */ package main +import ( + "strings" + "fmt" +) + func main() { s := "the sky is blue" - reverseWords(s) + fmt.Println(reverseWords(s)) } // @lc code=start func reverseWords(s string) string { - result := []byte{} + result := new(strings.Builder) - for i := len(s) - 1; i >= 0; i-- { - ans := []byte{} - hasWord := false - for i >= 0 && s[i] == byte(' ') { - i-- - } - for i >= 0 && s[i] != byte(' ') { - hasWord = true - ans = append([]byte{s[i]}, ans...) - i-- + i := len(s) - 1 + + for i >= 0{ + j := i + for j >= 0 && s[j] == byte(' ') { + j-- } - if hasWord { - ans = append(ans, byte(' ')) - result = append(result, ans...) + end := j + for j >= 0 && s[j] != byte(' ') { + j-- } + start := j + + result.Write([]byte(s[start+1:end+1])) + result.WriteByte(byte(' ')) + + + i = j } - return string(result[:len(result)-1]) + rt := result.String() + return string(rt[:len(rt)-1]) } // @lc code=end