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.

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"

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

如果想查看本题目是哪家公司的面试题,请参考以下免费链接: https://leetcode.jp/problemdetail.php?id=1427

解题思路分析:

  1. 向左变换n个字符的含义实际上是,将字符串分割为n和length-n两个部分,然后将两部分交换。比如abcdef,向左变换2,我们可以将字符串分割为ab和cdef两部分,然后将两个部分交换得到cdef ab
  2. 向右变换n个字符的含义是,将字符分割为length-n和n两个部分,然后将两部分交换。
  3. 注意,如果n大于length,n等于n与length的余数。
  4. 将字符串变换为字符数组后再对其操作可提高解题效率(java语言)

实现代码:

public String stringShift(String s, int[][] shift) {
    char[] arr = s.toCharArray();
    for(int[] sh : shift){
        char[] temp=new char[arr.length];
        int splitIndex=0;
        sh[1]=sh[1]%arr.length;
        if(sh[0]==0){
            splitIndex=sh[1];
        }else{
            splitIndex=arr.length-sh[1];
        }
        int index=0;
        for(int i=splitIndex;i<arr.length;i++){
            temp[index]=arr[i];
            index++;
        }
        for(int i=0;i<splitIndex;i++){
            temp[index]=arr[i];
            index++;
        }
        arr=temp;
    }
    return String.valueOf(arr);
}

本题解法执行时间为0ms。

Runtime: 0 ms, faster than 100.00% of Java online submissions for Perform String Shifts.

Memory Usage: 37.6 MB, less than 100.00% of Java online submissions for Perform String Shifts.

本网站文章均为原创内容,并可随意转载,但请标明本文链接
如有任何疑问可在文章底部留言。为了防止恶意评论,本博客现已开启留言审核功能。但是博主会在后台第一时间看到您的留言,并会在第一时间对您的留言进行回复!欢迎交流!
本文链接: http://leetcode.jp/leetcode-1427-perform-string-shifts-解题思路分析/
此条目发表在leetcode分类目录,贴了, , 标签。将固定链接加入收藏夹。

发表评论

您的电子邮箱地址不会被公开。