编程题--移动字符串移动

题目:把一个字符串的大写字母放到字符串的后面,各个字符的相对位置不变,且不能申请额外的空间。(应该指常数空间复杂度)

思路:从前到后扫描一遍字符串,每次将一块连续的小写字母和它之前的连续的大写字母交换位置。

代码:

#include<iostream>
#include<string>
using namespace std;
bool isUp(char& a) {
    if (a >= 'A'&&a <= 'Z')
        return true;
    else
        return false;
}
int main() {
    string s;
    while (cin >> s) {
        //u:大写字母起始点-1;l:小写字母起始点-1;c:当前扫描位置。
        int u, l, c=0;
        int size = s.size();
        //略过开头的小写字母
        while (c<size&&!isUp(s[c]))
            c++;
        //交换连续的l-u个大写字母和c-l个小写字母
        for (u = c, l = c; c < size+1; c++) {
            //当前字母大写
            if (c==size||isUp(s[c])) {
                if (u < l&&l < c) {
                    int ln = c - l;
                    int n = c - u;
                    //交换
                    int count = 0;
                    int start = u;
                    do {
                        char tmp1 = s[start];
                        for (size_t i = start +ln; i != start;)
                        {
                            char tmp2 = s[i];
                            s[i] = tmp1;
                            tmp1 = tmp2;
                            count++;
                            i += ln;
                            i = (i - u) % n + u;
                        }
                        s[start] = tmp1;
                        count++;
                        start++;
                    } while (count < n);
                    u += ln;
                    l = c;
                }
                l++;
            }
            //当前字母小写,什么都不做
        }
        cout << s << endl;
    }
}

对于连续m个大写字母和n个小写字母。m+n次移动可以将m个大写字母后移n位。效率高于另一种最简单的方法:

#include<iostream>
#include<string>
using namespace std;

bool isCap(char c)
{
    if (c >= 'A' && c <= 'Z')
        return true;
    else
        return false;
}

void mSwap(char &a, char &b)
{
    if (a != b)
    {
        a ^= b;
        b ^= a;
        a ^= b;
    }
}

int main()
{
    string s;
    while (cin >> s)
    {
        int len = s.size();
        int end = len;
        for (int i = 0; i<end; ++i)
        {
            if (isCap(s[i]))
            {
                int j = i;
                for (; j<len- 1; ++j)
                    mSwap(s[j], s[j + 1]);
                --end;
                --i;
            }
        }
        cout << s <<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值