1.把一个字符串的大写字母放到字符串的后面,各个字符的相对位置不变,且不能申请额外的空间
分析:
利用插入排序的思想,从字符串的第二个位置开始扫描,如果扫到小写字母,则该字母就是待处理的字符,将其标记,在该位置向前扫,如果是大写字母,则依次往后移动,直到向前遇到小写字母,空出来的位置放入标记字符,接着往后扫描,重复这几步
插入排序得思想
void InsertionSort(int *a, int len)
{
for (int j=1; j<len; j++)
{
int key = a[j];
int i = j-1;
while (i>=0 && a[i]>key)
{
a[i+1] = a[i];
i--;
}
a[i+1] = key;
}
}
完整源码
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
//类似前后两个指针,分别从前到后,从后到前,交换对应两个位置的字符。但是相对位置改变了。
string upperBehind(string& s)
{
int length = s.length();
int i = 0;
int j = length - 1;
while (i<j)
{
while (!isupper(s[i])&&i<j)//找到第一个大写字母
{
i++;
}
while (!islower(s[j])&&j>i)//找到第一个小写字母
{
j--;
}
if (i < j)//此时的交换两个位置的值
{
char temp = s[i];
s[i] = s[j];
s[j] = temp;
i++; j--;
}
}
return s;
}
//借用插入排序的思想,可以保持交换之后的位置的顺序不变
string upperBehind2(string& s)
{
int length = s.length();
//从第二个位置开始
for (int i = 1; i < length;i++)
{
if (islower(s[i]))//找到后面的小写字母插入到前面
{
char key = s[i];
int j = i - 1;
while (j >= 0 && isupper(s[j]))
{
s[j + 1] = s[j];
j--;
}
s[j + 1] = key;
}
}
return s;
}
int main()
{
string s1 ;
while (cin >> s1)
{
string results1 = upperBehind2(s1);
cout << results1 << endl;
}
//system("pause");
return 0;
}