【算法题】连续反转字符串

一个长度为n的字符串s和一个整数k,依次按照"i = 1,2, … ,n-k+1"的顺序操作得到的字符串:
将字符串s的第 i 个字符至第 i+k-1 之间的所有字符翻转。
求出最终状态的字符串。
例如:n是5,k是3,s是"hello"。
i = 1时,翻转[1,3]之间的字符,得到"lehlo"。
i = 2时,翻转[2,4]之间的字符,得到"heo"。
i = 3时,翻转[3,5]之间的字符,得到"loeh"。
因此,最终的s为“lloeh"。

输入描述
第一行输入正整数n,k。
第二行输入仅由小写字母构成的字符串s。

输出描述
输出s经过翻转后的最终状态。
示例 1
输入

5 3
hello

输出

lloeh

示例 2
输入

8 4
nowcoder

输出

odernowc
从样例找出的规律:
1 hello
2 elloh
3 lloeh
4 lohel
5 olleh

1 nowcoder
2 owcodern
3 wcoderno
4 coderwon
5 odernowc
6 derocwon
7 ernowcod
8 redocwon

思路:

如果k== 1,则输出原字符串,如果k== n,则简单反转整个字符串。

如果 k>1 && k<n 时
n和k奇偶性不同,则直接把前k-1个字符移动到字符串末尾
n和k奇偶性相同,则把前k-1个字符反转后,将其移动到末尾

Java代码:

import java.util.Scanner;

public class Bl {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int k = scanner.nextInt();
        scanner.nextLine();
        String s = scanner.nextLine();

        if (k <= 1) {
            System.out.println(s);
        } else if (k >= n) {
            System.out.println(new StringBuilder(s).reverse().toString());
        } else {
			String front = s.substring(0, k - 1);
			String rest = s.substring(k - 1);
            if (n % 2 == k % 2) { //奇偶性
                front = new StringBuilder(front).reverse().toString();
            }
            String result = rest + front;
            System.out.println(result);
        }
    }
}

代码未经题目验证

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值