题目:把一个字符串的大写字母放到字符串的后面,各个字符的相对位置不变,且不能申请额外的空间。
分别转自:
https://blog.csdn.net/z174432/article/details/79815088
https://blog.csdn.net/inite/article/details/79634900
https://blog.csdn.net/weixin_40149887/article/details/79749542
#include <iostream>
#include <cmath>
using namespace std;
int is_up(char a) {
return a >= 'A' && a <= 'Z';
}
int is_low(char a) {
return a >= 'a' && a <= 'z';
}
int main() {
string A;
cin >> A;
int N = A.size(), up = N - 1; // up从后往前遍历字符串
while (up >= 0) {
while (up >= 0 && is_low(A[up])) { // 找到第一个字符是大写字母
--up;
}
if (up < 0) { // 注意边界
break;
}
for (int i = up + 1; i < N; i++) { // 反复和邻位小写字符交换
if (is_up(A[i])) { // 直到邻位是一个大写字母
--up; // 更新up-----up前移
break;
}
char t = A[i]; // 交换
A[i] = A[i-1];
A[i-1] = t;
}
if (up == N-1) { // 如果最后up是最后一位字符
--up; // 需要更新up
}
}
cout << A << endl;
}
python版
#coding=utf-8
def houyi(nums):
i=len(nums)-1
j=len(nums)-1
while i>=0 and j>=0:
while ord(nums[j])>=65 and ord(nums[j])<=90:
j=j-1
while ord(nums[i])>=97:
i=i-1
if i<j:
nums.insert(j,nums.pop(i))
i=i-1
s='AkleBiCeilD'
s=list(s)
houyi(s)
for i in s:
print(i,end='')
另一c++版本
#include <iostream>
#include <queue>
using namespace std;
int main()
{
char str[1200];
while (scanf("%s",str)!=EOF){
queue<char> pqA, pqa;//使用队列分别存储大写字母和小写字母。
for (int i = 0; str[i]; ++i){
if ('A' <= str[i] && str[i] <= 'Z'){
pqA.push(str[i]);
}
else{
pqa.push(str[i]);
}
}
int j = 0;
while (!pqa.empty()){
str[j++] = pqa.front();
pqa.pop();
}
while (!pqA.empty()){
str[j++] = pqA.front();
pqA.pop();
}
cout << str << endl;
}
return 0;
}