LeetCode 423. Reconstruct Original Digits from English
Given a non-empty string containing an out-of-order English representation of digits 0-9
, output the digits in ascending order.
Note:
- Input contains only lowercase English letters.
- 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.
- Input length is less than 50,000.
Example 1:
Input: "owoztneoer" Output: "012"
Example 2:
Input: "fviefuro" Output: "45"
【题目分析】
从一堆数字的英文字母的乱序排列中还原出所有包含的数字,并且按照大小排序后以字符串的形式返回。
【思路】
对字符串中的字符进行计数,根据这些字符与数字的关系可以直接得到结果。
例如:字符z只在zero中出现,字符w只在two中出现,字符x只在six中出现,字符g只在eigth中出现,字符u只在four中出现
那么我们根据z,w,x,g,u的个数就可以知道0,2,6,8,4的个数。
对于剩下的one,three,five,seven,one可以由字符o的个数减去在0,2,4,6,8中出现的o的个数。
three可以由字符h的个数减去字符t,r,e在0,2,4,6,8中出现的个数
同理可以得到剩下的数字的个数
【java代码1】
1 public class Solution { 2 public String originalDigits(String s) { 3 int[] temp = new int[26]; 4 int[] digit = new int[10]; 5 6 for(int i = 0; i < s.length(); i++) { 7 temp[s.charAt(i)-97]++; 8 } 9 10 digit[0] = temp['z' -97]; 11 digit[2] = temp['w' -97]; 12 digit[6] = temp['x' -97]; 13 digit[8] = temp['g' -97]; 14 digit[4] = temp['u' -97]; 15 16 digit[1] = temp['o' -97] - (digit[0] + digit[2] + digit[4]); 17 digit[3] = temp['h' -97] - digit[8]; 18 digit[5] = temp['f' -97] - digit[4]; 19 digit[7] = temp['s' -97] - digit[6]; 20 digit[9] = temp['i' -97] - (digit[6] + digit[8] + digit[5]); 21 22 StringBuilder sb = new StringBuilder(); 23 for(int i = 0; i < digit.length; i++){ 24 for(int j = 0; j < digit[i]; j++){ 25 sb.append(i+""); 26 } 27 } 28 return sb.toString(); 29 } 30 }
【java代码2】
1 markieff 2 Reputation: 58 3 The idea is: 4 5 for zero, it's the only word has letter 'z', 6 for two, it's the only word has letter 'w', 7 ...... 8 so we only need to count the unique letter of each word, Coz the input is always valid. 9 10 Code: 11 12 public String originalDigits(String s) { 13 int[] count = new int[10]; 14 for (int i = 0; i < s.length(); i++){ 15 char c = s.charAt(i); 16 if (c == 'z') count[0]++; 17 if (c == 'w') count[2]++; 18 if (c == 'x') count[6]++; 19 if (c == 's') count[7]++; //7-6 20 if (c == 'g') count[8]++; 21 if (c == 'u') count[4]++; 22 if (c == 'f') count[5]++; //5-4 23 if (c == 'h') count[3]++; //3-8 24 if (c == 'i') count[9]++; //9-8-5-6 25 if (c == 'o') count[1]++; //1-0-2-4 26 } 27 count[7] -= count[6]; 28 count[5] -= count[4]; 29 count[3] -= count[8]; 30 count[9] = count[9] - count[8] - count[5] - count[6]; 31 count[1] = count[1] - count[0] - count[2] - count[4]; 32 StringBuilder sb = new StringBuilder(); 33 for (int i = 0; i <= 9; i++){ 34 for (int j = 0; j < count[i]; j++){ 35 sb.append(i); 36 } 37 } 38 return sb.toString(); 39 }