[CareerCup][Google Interview] 排序字符串
Sort an input string according to the given order string. There might be characters in input string that are not present in the order string and vice-versa. The characters of input string that are not present in the order string should come at the end of the output string in any order. Write code...
Example: Sort("abdcdfs","dacg");
output: ddacfbs
方法1:考虑用一个图来保存字符的大小关系,这样排序字符串的时候可以根据各各字符的大小关系来排序。构建图O(m^2),m为关系字符串长度。排序O(nlogn)
1 #include <iostream> 2 #include <string> 3 #include <algorithm> 4 using namespace std; 5 6 bool isSmaller[256][256]; 7 8 bool comp(const char &lhs, const char &rhs) 9 { 10 return isSmaller[lhs][rhs]; 11 } 12 13 int main() 14 { 15 memset(isSmaller, false, sizeof(isSmaller)); 16 17 char s[] = "abdcdfs"; 18 string order = "dacg"; 19 20 for(int i = 0; i < order.size(); i++) 21 { 22 for(int j = i + 1; j < order.size(); j++) 23 isSmaller[order[i]][order[j]] = true; 24 for(int k = 0; k < 256; k++) 25 if (!isSmaller[k][order[i]]) 26 isSmaller[order[i]][k] = true; 27 } 28 29 int len = strlen(s); 30 31 sort(s, s + len, comp); 32 33 cout << s << endl; 34 }
方法2:可以用一个hash表来保存在order中的字符出现个数,然后把未在order中出现的字符放后面。整个算法复杂度O(n)
1 #include <iostream> 2 #include <map> 3 #include <string> 4 using namespace std; 5 6 void Sort(string &s, string &order) 7 { 8 int count[256]; 9 10 memset(count, -1, sizeof(count)); 11 12 for(int i = 0; i < order.size(); i++) 13 count[order[i]] = 0; 14 15 int i = 0; 16 int j = s.size() - 1; 17 18 while(i <= j) 19 { 20 if (count[s[i]] >= 0) 21 { 22 count[s[i]]++; 23 i++; 24 } 25 else 26 { 27 char c = s[i]; 28 s[i] = s[j]; 29 s[j] = c; 30 j--; 31 } 32 } 33 34 int index = 0; 35 36 for(int i = 0; i < order.size(); i++) 37 for(int j = 0; j < count[order[i]]; j++) 38 s[index++] = order[i]; 39 } 40 41 int main() 42 { 43 string s = "abdcdfs"; 44 string order = "dacg"; 45 46 Sort(s, order); 47 48 cout << s << endl; 49 }