左旋转字符串

2020-07-28  本文已影响0人  Crazy_Bear
public class Solution {
    public String LeftRotateString(String str,int n) {
        if(str.length() == 0) return str;
        char[] arr = str.toCharArray();
        reverse(arr, 0, n-1);
        reverse(arr, n, str.length()-1);
        reverse(arr, 0, str.length()-1);
        StringBuilder sb = new StringBuilder();
        for(char ch:arr){
            sb.append(ch);
        }
        return sb.toString();
    }
    public void reverse (char[] str, int i, int j){
        while(i<j){
            char tmp = str[i];
            str[i] = str[j];
            str[j] = tmp;
            i++;
            j--;
        }
    }
}
class Solution {
public:
    string LeftRotateString(string str, int n) {
        if(str.empty()) return "";
        string str1=str.substr(0,n);
        string str2=str.substr(n);
        string str3=str2+str1;
        return str3;
    }
};
上一篇下一篇

猜你喜欢

热点阅读