423. Reconstruct Original Digits from English

来源:互联网 发布:关节机器人编程 编辑:程序博客网 时间:2024/05/19 01:33

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"
思路:

z 0

w 2

u 4

x 6

g 8

h 3 8

f 4 5

S 6 7

O 0 12 4

i 5 68 9

在遍历的时候判断字母比较慢,所以统一先统计字母个数,然后在统计数字个数。

public class Solution {    public String originalDigits(String s) {int[] letters = new int[26];int[] count = new int[10];for (int i = 0; i < s.length(); i++) {letters[s.charAt(i) - 'a']++;}count[0] = letters['z' - 'a'];count[2] = letters['w' - 'a'];count[4] = letters['u' - 'a'];count[6] = letters['x' - 'a'];count[8] = letters['g' - 'a'];count[3] = letters['h' - 'a'] - count[8];count[7] = letters['s' - 'a'] - count[6];count[5] = letters['f' - 'a'] - count[4];count[1] = letters['o' - 'a'] - count[0] - count[2] - count[4];count[9] = letters['i' - 'a'] - count[5] - count[6] - count[8];StringBuffer buffer = new StringBuffer();for (int i = 0; i < count.length; i++) {for (int j = 0; j < count[i]; j++) {buffer.append(i);}}return buffer.toString();            }}



0 0
原创粉丝点击