千家信息网

Lintcode8 Rotate String solution 题解

发表于:2024-10-28 作者:千家信息网编辑
千家信息网最后更新 2024年10月28日,【题目描述】Given a string and an offset, rotate string by offset. (rotate from left to right)给定一个字符串和一个偏移
千家信息网最后更新 2024年10月28日Lintcode8 Rotate String solution 题解

【题目描述】

Given a string and an offset, rotate string by offset. (rotate from left to right)

给定一个字符串和一个偏移量,根据偏移量旋转字符串(从左向右旋转)

【题目链接】

http://www.lintcode.com/en/problem/rotate-string/

【题目解析】

常见的翻转法应用题,仔细观察规律可知翻转的分割点在从数组末尾数起的offset位置。先翻转前半部分,随后翻转后半部分,最后整体翻转。

源码分析:异常处理,A为空或者其长度为0;offset可能超出A的大小,应模len后再用;三步翻转法。Python 虽没有提供字符串的翻转,但用 slice 非常容易实现,非常 Pythonic!

复杂度分析:翻转一次时间复杂度近似为 O(n)O(n)O(n), 原地交换,空间复杂度为 O(1)O(1)O(1). 总共翻转3次,总的时间复杂度为 O(n)O(n)O(n), 空间复杂度为 O(1)O(1)O(1).

【答案链接】

http://www.jiuzhang.com/solution/rotate-string/


0