[LeetCode] 1427. Perform String Shifts

You are given a string s containing lowercase English letters, and a matrix shift, where shift[i] = [direction, amount]:

  • direction can be 0 (for left shift) or 1 (for right shift). 
  • amount is the amount by which string s is to be shifted.
  • A left shift by 1 means remove the first character of s and append it to the end.
  • Similarly, a right shift by 1 means remove the last character of s and add it to the beginning.

Return the final string after all operations.

Constraints:

  • 1 <= s.length <= 100
  • s only contains lower case English letters.
  • 1 <= shift.length <= 100
  • shift[i].length == 2
  • 0 <= shift[i][0] <= 1
  • 0 <= shift[i][1] <= 100

Example 1:

Input: s = "abc", shift = [[0,1],[1,2]]
Output: "cab"
Explanation: 
[0,1] means shift to left by 1. "abc" -> "bca"
[1,2] means shift to right by 2. "bca" -> "cab"

Example 2:

Input: s = "abcdefg", shift = [[1,1],[1,1],[0,2],[1,3]]
Output: "efgabcd"
Explanation:  
[1,1] means shift to right by 1. "abcdefg" -> "gabcdef"
[1,1] means shift to right by 1. "gabcdef" -> "fgabcde"
[0,2] means shift to left by 2. "fgabcde" -> "abcdefg"
[1,3] means shift to right by 3. "abcdefg" -> "efgabcd"

题意是给一个string S和一个二维数组shift,请你根据shift里面的情况改动S,最后输出S被修改过后的结果。思路是首先遍历shift,判断出最后S到底是往左shift还是往右shift,用一个变量count记录。同时需要注意的是如果这个count的长度大于S的长度,需要取模。最后用substring函数看到底是S的两个substring到底应该如何拼接。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public String stringShift(String s, int[][] shift) {
 3         int count = 0;
 4         for (int[] value : shift) {
 5             if (value[0] == 0) {
 6                 count += value[1];
 7             } else {
 8                 count -= value[1];
 9             }
10         }
11         count = count % s.length();
12         if (count > 0) {
13             s = leftShift(s, count);
14         } else if (count < 0) {
15             s = rightShift(s, -count);
16         }
17         return s;
18     }
19     
20     public static String leftShift(String s, int num) {
21         return s.substring(num) + s.substring(0, num);
22     }
23     
24     public static String rightShift(String s, int num) {
25         return s.substring(s.length() - num) + s.substring(0, s.length() - num);
26     }
27 }

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/12710128.html