Leetcode-423. Reconstruct Original Digits from English

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————

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"
这个题目主要是找0-9字母的规律,然后统计一下字母出现的个数之后,就很清楚了。比较繁琐,不难。 Your runtime beats 24.54% of java submissions.

public class Solution {
    public String originalDigits(String s) {
        int[] count = new int[10];
	
	for(int i = 0 ; i < s.length(); i ++){
		if(s.charAt(i) == 'z') count[9] ++;
		else if(s.charAt(i) == 'w') count[0] ++;
		else if(s.charAt(i) == 'g') count[1] ++;
		else if(s.charAt(i) == 'x') count[2] ++;
		else if(s.charAt(i) == 's') count[3] ++;
		else if(s.charAt(i) == 'h') count[4] ++;
		else if(s.charAt(i) == 'v') count[5] ++;
		else if(s.charAt(i) == 'f') count[6] ++;
		else if(s.charAt(i) == 'o') count[7] ++;
		else if(s.charAt(i) == 'n') count[8] ++;
	}
	int[] numbers = new int[10];
	if(count[9] != 0){numbers[0] = count[9];count[7] -= numbers[0];}
	if(count[0] != 0){numbers[2] = count[0];count[7] -= numbers[2];}
	if(count[1] != 0){numbers[8] = count[1];count[4] -= numbers[8];}
	if(count[2] != 0){numbers[6] = count[2];count[3] -= numbers[6];}
	if(count[3] != 0){numbers[7] = count[3];count[8] -= numbers[7];count[5]-=numbers[7];}
	if(count[4] != 0){numbers[3] = count[4];}
	if(count[5] != 0){numbers[5] = count[5];count[6] -= numbers[5];}
	if(count[6] != 0){numbers[4] = count[6];count[7] -= numbers[4];}
	if(count[7] != 0){numbers[1] = count[7];count[8] -= numbers[1];}
	if(count[8] != 0){numbers[9] = count[8]/2;}
	StringBuffer sb = new StringBuffer("");
	for(int i = 0 ; i < 10; i++){
		for(int j = 0; j < numbers[i];j++)
			sb.append(i);
	}
	return sb.toString();
    }
}




你可能感兴趣的:(算法,java,leetcode,算法)