class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param s string字符串
     * @param n int整型
     * @return string字符串
     */
    string trans(string s, int n) {
        // write code here
        string res = "";
        string tmp = "";
        stack<char> sta;
        for (int i = n - 1; i >= 0; i--) {
            char tmp_ch = s[i];
            if (tmp_ch == ' ') tmp += tmp_ch;
            else if (tmp_ch >= 'A' && tmp_ch <= 'Z') tmp += tolower(tmp_ch);
            else if (tmp_ch >= 'a' && tmp_ch <= 'z') tmp += toupper(tmp_ch);
            else return "";
        }
        for (int i = 0; i < tmp.size(); i++) {
            if (tmp[i] != ' ') {
                sta.push(tmp[i]);
            } else {
                while (!sta.empty()) {
                    res += sta.top();
                    sta.pop();
                }
                res += ' ';
            }
        }
        while (!sta.empty()) {
            res += sta.top();
            sta.pop();
        }
        return res;
    }
};