剑指 Offer 58 - II. 左旋转字符串
字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。
示例 1:
输入: s = "abcdefg", k = 2 输出: "cdefgab"
示例 2:
输入: s = "lrloseumgh", k = 6 输出: "umghlrlose"
限制:
1 <= k < s.length <= 10000
原站题解
rust 解法, 执行用时: 0 ms, 内存消耗: 2.1 MB, 提交时间: 2023-09-12 20:21:12
impl Solution {pub fn reverse_left_words(s: String, n: i32) -> String {String::from(&s[n as usize..]) + &s[..n as usize]/*let n = n as usize;[&s[n..], &s[..n]].concat()*/}}
cpp 解法, 执行用时: 4 ms, 内存消耗: 7.1 MB, 提交时间: 2023-09-12 20:19:53
//方法1---借助额外字符串class Solution {public:string reverseLeftWords(string s, int n) {string ans = s;int length = s.size();for(int i=0;i<length;i++){ans[(i+length-n)%length] = s[i];}return ans;}};//方法2---在原字符串上修改/*class Solution {public:string reverseLeftWords(string s, int n) {//对前n个字符进行翻转reverse(s.begin(),s.begin()+n);//对剩下的字符进行翻转reverse(s.begin()+n,s.end());//对整个字符串进行翻转reverse(s.begin(),s.end());return s;}};*/
java 解法, 执行用时: 5 ms, 内存消耗: 42.2 MB, 提交时间: 2023-09-12 20:18:35
class Solution {public String reverseLeftWords(String s, int n) {StringBuilder res = new StringBuilder();for(int i = n; i < n + s.length(); i++)res.append(s.charAt(i % s.length()));return res.toString();}}
java 解法, 执行用时: 3 ms, 内存消耗: 42.4 MB, 提交时间: 2023-09-12 20:18:00
class Solution {public String reverseLeftWords(String s, int n) {StringBuilder res = new StringBuilder();for(int i = n; i < s.length(); i++)res.append(s.charAt(i));for(int i = 0; i < n; i++)res.append(s.charAt(i));return res.toString();}}
java 解法, 执行用时: 0 ms, 内存消耗: 41.1 MB, 提交时间: 2023-09-12 20:17:40
class Solution {public String reverseLeftWords(String s, int n) {return s.substring(n, s.length()) + s.substring(0, n);}}
php 解法, 执行用时: 8 ms, 内存消耗: 19.2 MB, 提交时间: 2023-09-12 20:17:07
class Solution {/*** @param String $s* @param Integer $n* @return String*/function reverseLeftWords($s, $n) {return substr($s, $n) . substr($s, 0, $n);}}
golang 解法, 执行用时: 0 ms, 内存消耗: 3.1 MB, 提交时间: 2020-11-09 23:09:34
func reverseLeftWords(s string, n int) string {return s[n:] + s[:n]}
python3 解法, 执行用时: 40 ms, 内存消耗: 13.6 MB, 提交时间: 2020-11-09 23:08:32
class Solution:def reverseLeftWords(self, s: str, n: int) -> str:return s[n:] + s[:n]