加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang的表格驱动测试

发布时间:2020-12-16 09:25:13 所属栏目:大数据 来源:网络整理
导读:一、leetcode的算法题 package main import ( " fmt " " strings " )func lengthOfNonRepeatingSubStr(s string)int{ lastOccurred : = make(map[rune]int) start: = 0 maxLength: = 0 // 将字符串转成 ASCII 码的切片,循环获取下标与值 for i,ch:= range [

一、leetcode的算法题

package main

import (
    "fmt"
    "strings"
)

func lengthOfNonRepeatingSubStr(s string)int{
    lastOccurred :=make(map[rune]int)
    start:=0
    maxLength:=0
    //将字符串转成 ASCII 码的切片,循环获取下标与值
    for i,ch:=range []rune(s){
        if lastI,ok:=lastOccurred[ch];ok && lastI>=start{
            start=lastOccurred[ch]+1
        }
        if i-start+1>maxLength {
            maxLength=i-start+1
        }
        lastOccurred[ch]=i
    }
    return maxLength
}
func main() {
    fmt.Println(
        lengthOfNonRepeatingSubStr("abcabcbb"),lengthOfNonRepeatingSubStr("bbbbb"),lengthOfNonRepeatingSubStr("阿斯顿法国规划开发阿斯顿发放"))

    fmt.Println([]byte("asfsawersd"))

    str1:="sdfsad asdfsadf sad;fasfd"
    s:=strings.Fields(str1)
    for index,value:=range s {
        fmt.Println(index,value)
    }
}

二、普通测试代码

package main

import "testing"

func TestSubstr(t *testing.T)  {
    tests:=[]struct{
        s string
        ans int
    }{
        {"abssafds",4},{"pwwkew",3},{"",0},{"b",1},{"bbbbbbbb",{"asadfasdf",}

    for _,tt:=range tests {
        actual:=lengthOfNonRepeatingSubStr(tt.s)
        if actual !=tt.ans{
            t.Errorf("got %d for input %s:"+"expected %d",actual,tt.s,tt.ans)
        }
    }
}

#测试通过
#=== RUN   TestSubstr
#--- PASS: TestSubstr (0.00s)
#PASS

#测试错误
#修改错误的数据{"pwwkew",2},
#=== RUN   TestSubstr
#--- FAIL: TestSubstr (0.00s)
#    leetcode_test.go:21: got 3 for input pwwkew:expected 2
#FAIL

三、性能测试代码

func BenchmarkSubstr(b *testing.B){
    s:="黑化肥挥发发灰会花飞灰化肥挥发发黑会飞花"
    ans:=8

    for i:=0;i<b.N;i++{
        actual:=lengthOfNonRepeatingSubStr(s)
        if actual !=ans {
            b.Errorf("got %d for input %s; "+"expected %d",s,ans)
        }
    }
}

#执行结果
#goos: windows
#goarch: amd64
#pkg: awesomeProject/leetcode
#运行了100万次,每次运行用了1362ns
#BenchmarkSubstr-8        1000000          1361 ns/op
#PASS

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读