791. Custom Sort String
791. Custom Sort String Use char[] array
use hashmap =============================== class Solution { public String customSortString(String S, String T) { StringBuilder sb = new StringBuilder(); HashMap<Character, Integer> map = new HashMap<>(); for(char c : T.toCharArray()){ // T.toCharArray() Integer freq = map.get(c); if(freq == null){ map.put(c, 1); }else{ map.put(c, freq + 1); } } for(char c : S.toCharArray()){ Integer freq = map.get(c); // Integer, because might return null if(freq != null){ while(freq > 0){ sb.append(c); freq--; } map.remove(c); } } for(char c : map.keySet()){ int freq = map.get(c); while(freq > 0){ sb.append(c); freq--; } } return sb.toString(); } }
use int[] array ====================== class Solution { public String customSortString(String S, String T) { StringBuilder sb = new StringBuilder(); int[] count = new int[26]; for(char c : T.toCharArray()){ count[c - 'a']++; } for(char c : S.toCharArray()){ int freq = count[c - 'a']; if(freq > 0){ while(freq > 0){ sb.append(c); freq--; } count[c - 'a'] = 0; } } for(char c = 'a'; c <= 'z'; c++){ int freq = count[c - 'a']; if(freq != 0){ while (freq > 0){ sb.append(c); freq--; } } } return sb.toString(); } }
感觉自己的答案比较intuitive
===================== https://leetcode.com/problems/custom-sort-string/solution/ 一会再看下这个答案
Use char[] array
S and T are strings composed of lowercase letters. In S, no letter occurs more than once.
S was sorted in some custom order previously. We want to permute the characters of T so that they match the order that S was sorted. More specifically, if x occurs before y in S, then x should occur before y in the returned string.
Return any permutation of T (as a string) that satisfies this property.
Example : Input: S = "cba" T = "abcd" Output: "cbad" Explanation: "a", "b", "c" appear in S, so the order of "a", "b", "c" should be "c", "b", and "a". Since "d" does not appear in S, it can be at any position in T. "dcba", "cdba", "cbda" are also valid outputs.
posted on 2018-08-28 21:30 猪猪🐷 阅读(128) 评论(0) 收藏 举报
浙公网安备 33010602011771号