leetcode1427 - Perform String Shifts - easy

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.

 

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"

 

先计算net shifts,  再进行string的分割和拼接。N = array shift的长度, L = string s的长度,time complexity O(N+L) (step 1 traverse the array and step 2 perform a single string-shift operation)

注意substr的用法:

substr(pos) - 从index为pos(包含)直到end

substr(pos, len) - 从index为pos取len位

 

实现:

 1 class Solution {
 2 public:
 3     string stringShift(string s, vector<vector<int>>& shift) {
 4         
 5         if (shift.empty()) return s;
 6         
 7         int leftShifts = 0, rightShifts = 0;
 8         for (auto s : shift){
 9             if (s[0] == 0) leftShifts += s[1];
10             else rightShifts += s[1];
11         }
12         
13         if (leftShifts == rightShifts) return s;
14         
15         int n = s.size();
16         string res;
17         if (leftShifts > rightShifts){
18             leftShifts = (leftShifts-rightShifts)%n;
19             res = s.substr(leftShifts) + s.substr(0, leftShifts);
20         }else{
21             rightShifts = (rightShifts-leftShifts)%n;
22             res = s.substr(n-rightShifts) + s.substr(0, n-rightShifts);
23         }
24             
25         return res; 
26         
27     }
28 };

 

posted @ 2020-08-05 12:13  little_veggie  阅读(173)  评论(0)    收藏  举报