題解 | #重排字符串和數字#
重排字符串和數字
http://fangfengwang8.cn/questionTerminal/70be97a0060c474ebf5b2edce171f0ec
//> 字符串拆成兩個部分保存,C++貼 class Solution { public: /** * 代碼中的類名、方法名、參數名已經指定,請勿修改,直接返回方法規(guī)定的值即可 * * * @param text_source string字符串 原始輸入 * @return string字符串 */ string char_and_num_return(string text_source) { // write code here //> 保存字符 vector<string> strs; //> 保存數字 vector<long long> nums; string str = ""; int flag = 0; //> 加一個空格,把所有遍歷完 text_source += ' '; for (auto& ch : text_source) { if (ch == ' ') { //> 1 : 數字 //> 2 : 字符 if (flag == 1) { nums.emplace_back(stoll(str)); } else if (flag == 2) { strs.emplace_back(str); } flag = 0; str.clear(); } else if (ch >= '0' && ch <= '9') { flag = 1; str += ch; } else { flag = 2; str += ch; } } string ans = ""; //> 數字排序 sort(nums.begin(), nums.end()); if (!strs.empty()) { for (int i = 0; i < strs.size(); ++i) { ans += strs[i]; //> 最后一個空格 if (i != strs.size()- 1) ans += ' '; } } if (!nums.empty()) { if (!ans.empty()) ans += ' '; for (int i = 0; i < nums.size(); ++i) { ans += to_string(nums[i]); //> 最后一個空格 if (i != nums.size() - 1) ans += ' '; } } return ans; } };