华为机试:广场舞在编排舞蹈时,需要变换队形来体现团队协调性,假定参与者为字符串 str,调整的倍数为n,需要对从队伍的开头 n 个人进行位置互换

队伍变换 | 时间限制:1秒 | 内存限制:262144K

广场舞在编排舞蹈时,需要变换队形来体现团队协调性,假定参与者为字符串 str,调整的倍数为n,需要对从队伍的开头 n 个人进行位置互换

条件:
1、人数少于 n 个,保持不变。

示例1

输入

"abcdefg",2

输出

"badcfeg"

说明

abcdefg长度大于2,所以反转前两位字符得到ba,依次反转得到dc、fe,剩余g 保持不变,最后结果为ba + dc+ fe + g。

示例2

输入

"nowcoder",4

输出

"cwonredo"

说明

nowcoder 长度 > 4,依次反转得到cwon、redo,结果输出为 cwonredo。

cpp 复制代码
#include <iostream>
#include <cstring>

using namespace std;

void reverse(string &str, int start, int end) {
    while (start < end) {
        swap(str[start], str[end]);
        start++;
        end--;
    }
}

string transform(string str, int n) {
    int len = str.length();
    if (len < n) {
        return str;
    }
    int start = 0;
    int end = n - 1;
    while (end < len) {
        reverse(str, start, end);
        start += n;
        end += n;
    }
    return str;
}

int main() {
    string s;
    int n;
    cin >> s >> n;
    cout << transform(s, n) << endl;
    return 0;
}
相关推荐
u0104058361 天前
京东返利app的分布式ID生成策略:雪花算法在订单系统中的实践
分布式·算法
lingran__1 天前
速通ACM省铜第三天 赋源码(Double Perspective和Trip Shopping和Hamiiid, Haaamid... Hamid?)
c++·算法
凤城老人1 天前
C++使用拉玛努金公式计算π的值
开发语言·c++·算法
纪元A梦1 天前
贪心算法应用:配送路径优化问题详解
算法·贪心算法
C_player_0011 天前
——贪心算法——
c++·算法·贪心算法
kyle~1 天前
排序---插入排序(Insertion Sort)
c语言·数据结构·c++·算法·排序算法
Boop_wu1 天前
[数据结构] 队列 (Queue)
java·jvm·算法
安卓开发者1 天前
鸿蒙Next ArkWeb网页交互管理:从基础到高级实战
华为·交互·harmonyos
hn小菜鸡1 天前
LeetCode 3643.垂直翻转子矩阵
算法·leetcode·矩阵
ゞ 正在缓冲99%…1 天前
leetcode101.对称二叉树
算法