Leetcode 423. Reconstruct Original Digits from English

来源:互联网 发布:茶叶淘宝主图设计模板 编辑:程序博客网 时间:2024/05/21 07:47


Given a non-empty string containing an out-of-order English representation of digits 0-9, output the digits in ascending order.

Note:

  1. Input contains only lowercase English letters.
  2. Input is guaranteed to be valid and can be transformed to its original digits. That means invalid inputs such as "abc" or "zerone" are not permitted.
  3. Input length is less than 50,000.

Example 1:

Input: "owoztneoer"Output: "012"

Example 2:

Input: "fviefuro"Output: "45"


思路描述:

zero  one two three four five six seven eight nine

0         1     2      3       4      5     6      7      8        9

分析数字的字母构成,如果字符串含有 z,  则根据题目条件字符串总是有效的来看,必有一个  zero的组合在原串中,那么取出一个zero, 记录0的出现次数加1

再次循环,直至没有z为止。

 出现w,必有two

 出现u,必有four

 出现x,必有six

 出现g,必有 eight


以上完成后,剩下的数字仅仅剩下 one,  five, seven, three, nine

此时只需要在剩下的找标志性支付,f : five,  s : seven, h: three o : one


最后一轮,只剩nine,查找结束。以下为代码实现。



import "strings"

import "fmt"
func originalDigits(s string) string {
    s = strings.ToLower(s)
    var result0 [10]int
    for i := 0; i < 10; i++ {
        result0[i] = 0;
    }
    result := result0[:]
    var letterMap = make(map[rune]int)
    for _, c := range  s {
        _, ok := letterMap[c]
        if !ok {
            letterMap[c] = 1
        } else {
            count := letterMap[c]
            letterMap[c] = count + 1
        }
    }
   var numberMap = map[int][]rune {
        0 : []rune {'z','e','r','o'},
        1 : []rune {'o','n','e'},
        2 : []rune {'t','w','o'},
        3 : []rune {'t','h','r','e','e'},
        4 : []rune {'f','o','u','r'},
        5 : []rune {'f','i','v','e'},
        6 : []rune {'s','i','x'},
        7 : []rune {'s','e','v','e','n'},
        8 : []rune {'e','i','g','h','t'},
        9 : []rune {'n','i','n','e'},
    }
    
    
    // find w, h,u, x, g, z
    var para = map[rune]int {
        'z': 0,
        'w': 2,
        'u': 4,
        'x': 6,
        'g': 8,
    }
    
    genData(para,numberMap,letterMap,result)
    
    // find o,f,s
    var para1 = map[rune] int {
        'o': 1,
        'f': 5,
        's': 7,
        'h': 3,
0 0
原创粉丝点击