Go语言学习笔记————Codewar做题实录

Go 语言之前在写 6.824 的时候用过,现在单独拿出来学习一下,主要学习方式以在 codewar 做题为主

Vowel Count

https://www.codewars.com/kata/54ff3102c1bad923760001f3/train/go

这道题主要是借助于 strings 库中的 strings.ContainsAny 函数。官网上解答有借助于 switch

1
2
3
4
5
6
for _, c := range str {
switch c {
case 'a', 'e', 'i', 'o', 'u':
count++
}
}

还有借助于 strings.Count 单独统计每一个元音的数量的

1
2
3
4
vowels := []string{"a", "e", "i", "o", "u"}
for _, vowel := range vowels {
count += strings.Count(strn, vowel)
}

Two to One

https://www.codewars.com/kata/5656b6906de340bd1b0000ac/train/go

本题涉及排序和去重,主要是对 string 类型的理解。
string 实际上是只读的 byte 的 slicestring 可以和 []byte 进行互转。
在下面的代码中遇到报错,说 runebyte 的 type 是 mismatch 的。这是因为当使用 for range 遍历字符串时,每一次迭代得到一个 UTF-8 编码的 rune 对象,这个是和用 index 遍历不一样的。

1
2
for i, x := range(tot){
if x != tot[i-1]{

看了一下大众的答案,写的比我好。它使用 strings.Split 将字符串变成数组,再使用 sort.Strings 来排序,这样可以避免我上面操作 runebyte 的困扰

1
2
3
4
5
6
7
8
9
10
11
12
func TwoToOne(s1 string, s2 string) (res string) {
var arr []string
arr = strings.Split(s1+s2, "")
sort.Strings(arr)

for _, i := range arr {
if !(strings.Contains(res, i)) {
res += string(i)
}
}
return
}

Function 1 - hello world

https://www.codewars.com/kata/523b4ff7adca849afe000035/train/go

go 语言里面有个带变量名的返回值的特性,也就是说,我们可以在函数体中对函数返回值直接进行赋值,这有点类似 VB6 的特性了。

1
2
3
4
func greet() (hello string) {
hello = "hello world"
return
}

Multiples of 3 or 5

https://www.codewars.com/kata/514b92a657cdc65150000006/train/go

输出所有小于指定数的,有3或者5的因子的数的和。简单题。

Highest Scoring Word

https://www.codewars.com/kata/57eb8fcdf670e99d9b000272/train/go

貌似 sort.Sort 不是稳定排序,所以不能靠排序解决。
本题主要是几点:

  1. 创建动态长度的数组,一般用 make([]int, length) 这样,似乎 newvar 都不行
  2. 利用 math.Max 比较大小,会遇到 cannot use math.Max(score[i], mx) (type float64) as type int in assignment 的错误,查了一下,似乎 go 没有提供内置的整型的大小比较函数。。。

Valid Braces

https://www.codewars.com/kata/5277c8a221e209d3f6000b56/train/go

一个简单的括号匹配问题,主要涉及了下面的知识

  1. 创建并初始化 map,这个方法有点类似于 C++,其中中括号里面的是 Key

    1
    var lookup map[rune] rune = map[rune] rune{'{': '}', '[': ']', '(': ')'}

  2. 一般通过对一个动态大小的数组进行 append 和 slice 操作来实现

    1
    2
    3
    4
    5
    s := []rune{}
    // 添加元素到尾部
    s = append(s, x)
    // 删除尾部元素
    s = s[:len(s)-1]
  3. switch 语句和 C/C++ 差不多形式,但不需要显式 break 了

    1
    2
    3
    4
    5
    6
    switch x{
    case '{', '[', '(':
    s = append(s, x)
    case '}', ']', ')':
    ...
    }