/*
時間限制 C/C++ 3s 其他 6s, 空間限制 C/C++ 32768k 其他 65535k
題目描述
給定一個長度不限的字符串,請找出該字符串中出現次數最多的那個字符,並打印出該字符及其出現次數;
如果多個字符的出 現次數相同,只打印首個字符;輸出字符的大小寫格式要與輸 入保持一致,大小寫不敏感模式下,
輸出字符的大小寫格式與該 字符首次出現時的大小寫格式一致。實現時無需考慮非法輸。
輸入描述
輸入為 字符串大小寫敏感標記 其中"大小寫敏感標記"為可選參數,取值范圍為七yue|1fa1 se,txue表示大小寫敏感;缺省取值txue
例子: abcdabcde fa1e
輸出描述
輸出:字符出現次數 如果出現次數最多的字符有多個,輸出字典序最小的那個字 符。輸出的字符都為小寫字符
例子: a 2
*/
Python實現
1 str1 = input() 2 str2 = str1.split(" ") 3 sensitive = True 4 if str2[1] == "false": 5 sensitive = False 6 maxCount = 0 7 maxChar = "0" 8 if sensitive: 9 for c in str2[0]: 10 tmp = str2[0].count(c) 11 if tmp > maxCount: 12 maxCount = tmp 13 maxChar = c 14 else: 15 lc = str2[0].lower() 16 index = 0; 17 for c in lc: 18 tmp = lc.count(c) 19 if tmp > maxCount: 20 maxCount = tmp 21 maxChar = str2[0][index] 22 index += 1 23 print("%s %d" % (maxChar, maxCount))
C++實現,好像最終還有點問題。
1 #include<iostream> 2 using namespace std; 3 4 int main() 5 { 6 char c[60000] = { 0 }; 7 char s[5] = { 0 }; 8 unsigned int count[52] = { 0 }; 9 char output[52] = { 0 }; 10 memset(c, 0, 60000); 11 bool sensitive = true; 12 cin >> c; 13 cin >> s; 14 int i = 0; 15 int index = 0; 16 while ((i < 5) && (s[i] != 0)) 17 { 18 if (strcmp(&s[i + 1], "true")) 19 { 20 sensitive = true; 21 } 22 else 23 { 24 sensitive = false; 25 } 26 break; 27 28 i++; 29 } 30 int j = 0; 31 int max = 0, outputIndex = 0; 32 while ((j < 6000)&&(c[j]!=0)) 33 { 34 if (sensitive) 35 { 36 if (90 < c[j]) 37 { 38 index = c[j] - 'A'; 39 count[index]++; 40 if (output[index] == 0) 41 { 42 output[index] = c[j]; 43 } 44 if (max < count[index]) 45 { 46 max = count[index]; 47 outputIndex = index; 48 } 49 } 50 else 51 { 52 index = c[j] - 'a'; 53 count[index + 26]++; 54 if (output[index + 26] == 0) 55 { 56 output[index + 26] = c[j]; 57 } 58 if (max < count[index + 26]) 59 { 60 max = count[index + 26]; 61 outputIndex = index + 26; 62 } 63 } 64 } 65 else 66 { 67 if (90 < c[j]) 68 { 69 index = c[j] - 'A'; 70 } 71 else 72 { 73 index = c[j] - 'a'; 74 } 75 count[index]++; 76 if (output[index] == 0) 77 { 78 output[index] = c[j]; 79 } 80 if (max < count[index]) 81 { 82 max = count[index]; 83 outputIndex = index; 84 } 85 } 86 j++; 87 } 88 cout << output[outputIndex] << " " << max << endl; 89 system("pause"); 90 return 0; 91 }
注意編譯器不兼容的問題