题目描述
看了题目以后想到啥? 字符数量统计 银行家算法逐个拆解 建立数字 - 字符串的全局映射
思路 && 代码
抄答案了,采取了评论区三叶dalao的写法(不得不说,人家的处理写法是真的优雅),学习学习。
class Solution { static String [ ] ss = new String [ ] { "zero" , "one" , "two" , "three" , "four" , "five" , "six" , "seven" , "eight" , "nine" } ; static int [ ] priority = new int [ ] { 0 , 8 , 6 , 3 , 2 , 7 , 5 , 9 , 4 , 1 } ; public String originalDigits ( String s) { int [ ] counts = new int [ 26 ] ; for ( char c : s. toCharArray ( ) ) counts[ c - 'a' ] ++ ; StringBuilder sb = new StringBuilder ( ) ; for ( int i : priority) { int k = Integer . MAX_VALUE; for ( char c : ss[ i] . toCharArray ( ) ) k = Math . min ( k, counts[ c - 'a' ] ) ; for ( char c : ss[ i] . toCharArray ( ) ) counts[ c - 'a' ] -= k; while ( k-- > 0 ) sb. append ( i) ; } char [ ] cs = sb. toString ( ) . toCharArray ( ) ; Arrays . sort ( cs) ; return String . valueOf ( cs) ; }
}
class Solution { static String [ ] ss = new String [ ] { "zero" , "one" , "two" , "three" , "four" , "five" , "six" , "seven" , "eight" , "nine" } ; static int [ ] priority = new int [ ] { 0 , 8 , 6 , 3 , 2 , 7 , 5 , 9 , 4 , 1 } ; public String originalDigits ( String s) { int [ ] counts = new int [ 26 ] ; for ( char c : s. toCharArray ( ) ) counts[ c - 'a' ] ++ ; StringBuilder sb = new StringBuilder ( ) ; for ( int i : priority) { int k = Integer . MAX_VALUE; for ( char c : ss[ i] . toCharArray ( ) ) k = Math . min ( k, counts[ c - 'a' ] ) ; for ( char c : ss[ i] . toCharArray ( ) ) counts[ c - 'a' ] -= k; while ( k-- > 0 ) sb. append ( i) ; } char [ ] cs = sb. toString ( ) . toCharArray ( ) ; Arrays . sort ( cs) ; return String . valueOf ( cs) ; }
}