avatar

superorange0707

  • Homepage
  • Tag
  • Category
Home Leetcode-Left Roate the String
文章

Leetcode-Left Roate the String

Posted 2022-07-11
4~5 min read

Left Roate the String

leetcode: https://leetcode.cn/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof

Description:

The left rotation operation of a string is to transfer several characters in front of the string to the end of the string. Please define a function to implement the function of left rotation of strings. For example, input the string “abcdefg” and the number 2, the function will return the result “cdefgab” obtained by left-rotating two places.

Idea:

Solution1:

Step1: create new string, and split the original string according to the number, then combine them

this solution will cost more Space complexity

Code:

class Solution {
    public String reverseLeftWords(String s, int n) {
        String string1 ="";
        for(int i =n; i<s.length(); i++){
            string1 = string1 + s.charAt(i);
        }
        for(int i=0; i<n; i++){
            string1 += s.charAt(i);
        }
        return string1;
    }
}

Solution2:

Step1: Reverse the substring before the specific number

Step2: Reverse the substring after the number

Step3: Reverse the whole string

Code:

class Solution {
    public String reverseLeftWords(String s, int n) {
        char[] result = s.toCharArray();
        reverse(result,0,n-1);
        reverse(result,n,s.length()-1);
        reverse(result,0,s.length()-1);
        return new String(result);
    }
    public void reverse(char[]s, int i, int j){
        while(i<j){
            char temp = s[i];
            s[i] = s[j];
            s[j] = temp;
            i++;
            j--;
        }
    }
}
Leetcode
Leetcode String
Share

Further Reading

Apr 23, 2025

283 - Move Zero

[283 - Move Zero] 🔗 LeetCode Link Problem Description Given an integer array nums, move all 0's to the end of it while maintaining the relative order

Apr 23, 2025

27 - Remove Element

[27 - Remove Element] 🔗 LeetCode Link Problem Description Given an integer array nums and an integer val, remove all occurrences of val in nums in-pl

Apr 23, 2025

26 - Remove Duplicates from Sorted Array

[26 - Remove Duplicates from Sorted Array] 🔗 LeetCode Link Problem Description Given an integer array nums sorted in non-decreasing order, remove the

OLDER

Leetcode-151-Reverse Words in a String

NEWER

Leetcode-28-Implement strStr()-KMP

Recently Updated

  • Migrating Jenkins SCM Using GitLab from Bitbucket: SCM URL Bulk Replacement
  • 283 - Move Zero
  • 27 - Remove Element
  • 26 - Remove Duplicates from Sorted Array
  • Migrating from Bitbucket to GitLab? Here’s how to keep your teams moving without missing a beat!

Trending Tags

Course two pointer Binary Tree Hash SQL Leetcode Error Recording Gitlab Bitbucket Devops

Contents