華為OJ:字串排序
阿新 • • 發佈:2019-02-15
採用氣泡排序(穩定排序):
法1: 遇到非字母字元時,處理要小心。
#include<iostream> #include<string> using namespace std; int main() { string s,str; char tempc; while(getline(cin,str)) { int len = str.length(); for(int i = 0; i < len; i++) { for(int j = 0; j< len-i-1; j++) { int k = j; if(isalpha(str[j])) { while(k < len-1 && !isalpha(str[k+1])) k++; if(k == len-1) continue; if(tolower(str[j]) > tolower(str[k+1])) { tempc = str[j]; str[j] = str[k+1]; str[k+1] = tempc; } } else continue; } } cout << str << endl; } return 0; }
法2:藉助額外的空間來處理
#include <iostream> #include <string> using namespace std; int main() { string str; char tempc; while (getline(cin, str)) { string s; for (int i = 0; i<str.size(); i++) { if (isalpha(str[i])) s += str[i]; } for (int i = 0; i<s.size(); i++) { for (int j = 0; j<s.size() - i - 1; j++) { if (tolower(s[j]) > tolower(s[j + 1])) { tempc = s[j]; s[j] = s[j + 1]; s[j + 1] = tempc; } } } for (int i = 0, j = 0; i<str.size(); i++) { if (isalpha(str[i])) str[i] = s[j++]; } cout << str << endl; } return 0; }