一个长度为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);
}
}
}
代码未经题目验证