LeetCode 30天挑战 Day-14

LeetCode 30 days Challenge - Day 14

本系列将对LeetCode新推出的30天算法挑战进行总结记录,旨在记录学习成果、方便未来查阅,同时望为广大网友提供帮助。


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

Solution

题目要求分析:给定一个原始字符串以及一个位移指令集合shift,shift数组中,每个元素是一个二元组,依次表示对字符串进行的位移操作方向以及位数,要求返回最后处理完成的字符串。

解法:

本题提示中,说明了在限制条件下,直接暴力模拟也能通过,但这肯定不是我们想要的答案,为了尽可能减少“移动”操作,先来分析移动操作的特点:

  1. 方向0:向左移动amount个元素,实际上是将前amount个元素移动到字符串尾部
  2. 方向1:向右移动amount个元素,实际上是将后amount个元素移动到字符串头部

两次方向不同、amount相同的移动,将相互抵消:abcd -0,2-> cdab -1,2-> abcd

由此,推断出最便利的做法是,先遍历shift数组,记录最终需要移动的步数(final_amount),具体措施:

  1. 遇到方向0,final_amount减去对应amount;
  2. 遇到方向1,final_amount加上对应amount;

最后,根据final_amount的正负(注意对长度取模,长度为n的字符串移动n次将恢复原状),依据移动操作的特点进行处理即可。


string stringShift(string s, vector<vector<int>>& shift) {
    string res = "";
    int final_amount = 0;
    for (auto v : shift) final_amount += v[0] ? v[1] : -v[1];
    if (final_amount > 0) {
        final_amount %= s.length();
        res = s.substr(0, s.length() - final_amount);
        res = s.substr(s.length() - final_amount) + res;
    }
    else {
        final_amount = (-final_amount) % s.length();
        res = s.substr(final_amount);
        res += s.substr(0, final_amount);
    }
    return res;
}

传送门:Perform String Shifts

2020/4 Karl

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值