一、题目内容

image.png

二、题解

解法1:

思路

模拟,拼接

代码

  1. class Solution {
  2. public String reverseLeftWords(String s, int n) {
  3. char[] leftPrefix = new char[n];
  4. char[] ans = new char[s.length()];
  5. char[] chars = s.toCharArray();
  6. for (int i = 0; i < chars.length; i++) {
  7. if (i < n) {
  8. leftPrefix[i] = chars[i];
  9. } else {
  10. ans[i - n] = chars[i];
  11. }
  12. }
  13. for (int i = chars.length - n; i < chars.length; i++) {
  14. ans[i] = leftPrefix[i + leftPrefix.length - chars.length];
  15. }
  16. return new String(ans);
  17. }
  18. }

解法2:

思路

取模

代码

  1. class Solution {
  2. public String reverseLeftWords(String s, int n) {
  3. char[] ans = new char[s.length()];
  4. char[] chars = s.toCharArray();
  5. for (int i = n; i < chars.length + n; i++) {
  6. ans[i - n] = chars[i % chars.length];
  7. }
  8. return new String(ans);
  9. }
  10. }