按如下規則轉換字母:
Let's consider that a word has been typed with the Caps lock key accidentally switched on, if:
In this case we should automatically change the case of all letters. For example, the case of the letters that form words "hELLO", "HTTP", "z" should be changed.
單個大寫字母是否需要轉換?需要。cBCD -> Cbcd
Good -> Good
H -> h
h -> H
看似乎簡單,但是解決這個問題可以,要優雅地寫出程序,那麼就是不容易的了。
下面看我的程序,使用automata的知識,寫個小小的automata系統,優雅地解決這個問題:
#include#include #include using namespace std; enum CASE { ALL_UPPERS, ONLY_FIRST_LOWER, CORRECT, ILEGAL }; const static int trans[6][2] = { {1, 2}, //0 Init and Invalid {3, 5}, //1 first upper {4, 5}, //2 first lower {3, 5}, //3 all upper {4, 5}, //4 first low other upper {5, 5} }; //5 correct words CASE checkLetters(string &s) { int state = 0; for (int i = 0; i < s.size(); i++) { int input = -1; if ('A' <= s[i] && s[i] <= 'Z') input = 0; if ('a' <= s[i] && s[i] <= 'z') input = 1; if (-1 == input) return ILEGAL; state = trans[state][input]; } if (1 == state || 3 == state) return ALL_UPPERS; else if (2 == state || 4 == state) return ONLY_FIRST_LOWER; return CORRECT; } void transAllLowers(string &s) { for (int i = 0; i < s.size(); i++) { s[i] = s[i] - 'A' + 'a'; } } void transFirstUpper(string &s) { s[0] = s[0] - 'a' + 'A'; for (int i = 1; i < s.size(); i++) { s[i] = s[i] - 'A' + 'a'; } } void cAPSLOOCK() { string s; cin>>s; CASE C = checkLetters(s); if (ALL_UPPERS == C) transAllLowers(s); else if (ONLY_FIRST_LOWER == C) transFirstUpper(s); else if (ILEGAL == C) cout<<"ILEGAL", exit(0); cout<