C练题笔记之:Leetcode-1427. 字符串的左右移

    科技2022-07-11  85

    题目:

    给定一个包含小写英文字母的字符串 s 以及一个矩阵 shift,其中 shift[i] = [direction, amount]:

    direction 可以为 0 (表示左移)或 1 (表示右移)。 amount 表示 s 左右移的位数。 左移 1 位表示移除 s 的第一个字符,并将该字符插入到 s 的结尾。 类似地,右移 1 位表示移除 s 的最后一个字符,并将该字符插入到 s 的开头。 对这个字符串进行所有操作后,返回最终结果。

     

    示例 1:

    输入:s = "abc", shift = [[0,1],[1,2]] 输出:"cab" 解释: [0,1] 表示左移 1 位。 "abc" -> "bca" [1,2] 表示右移 2 位。 "bca" -> "cab" 示例 2:

    输入:s = "abcdefg", shift = [[1,1],[1,1],[0,2],[1,3]] 输出:"efgabcd" 解释:  [1,1] 表示右移 1 位。 "abcdefg" -> "gabcdef" [1,1] 表示右移 1 位。 "gabcdef" -> "fgabcde" [0,2] 表示左移 2 位。 "fgabcde" -> "abcdefg" [1,3] 表示右移 3 位。 "abcdefg" -> "efgabcd"

    提示:

    1 <= s.length <= 100 s 只包含小写英文字母 1 <= shift.length <= 100 shift[i].length == 2 0 <= shift[i][0] <= 1 0 <= shift[i][1] <= 100

    来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/perform-string-shifts 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    结果:

    解题思路:

    1,计算出总共左移或者右移了多少,并且将饶了几圈的通过取余算出实际走了多少

    2,通过区分左移和右移,按顺序赋值到新的数组中

    代码:

    char * stringShift(char * s, int** shift, int shiftSize, int* shiftColSize){ int len = strlen(s); int temp = 0; for(int i = 0; i < shiftSize; i++){ if(shift[i][0]) { temp -= shift[i][1]; } else { temp += shift[i][1]; } } if(temp < 0) { temp = -(abs(temp) % len); } else { temp = temp % len; } if(temp == 0) { return s; } char *retArr = (char *)malloc(sizeof(char) * (len + 1)); memset(retArr, '\0', len+1); if(temp > 0) { for(int i = 0; i < len; i++) { if(i + temp >= len) { retArr[i] = s[i + temp - len]; } else { retArr[i] = s[i + temp]; } } } else { for(int i = 0; i < len; i++) { if(i + temp < 0) { retArr[i] = s[len + temp + i]; } else { retArr[i] = s[i + temp]; } } } return retArr; }

     

    Processed: 0.019, SQL: 8