??算法,不如說它是一種思考方式??
算法專欄: ????123
一、??劍指 Offer 58 - II. 左旋轉(zhuǎn)字符串
- 題目描述:字符串的左旋轉(zhuǎn)操作是把字符串前面的若干個字符轉(zhuǎn)移到字符串的尾部。請定義一個函數(shù)實現(xiàn)字符串左旋轉(zhuǎn)操作的功能。比如,輸入字符串"abcdefg"和數(shù)字2,該函數(shù)將返回左旋轉(zhuǎn)兩位得到的結(jié)果"cdefgab"。
- 來源:力扣(LeetCode)
- 難度:簡單
- 提示:
1 <= k < s.length <= 10000 - 示例 1:
輸入: s = “abcdefg”, k = 2
輸出: “cdefgab”
??解題
1.直接使用字符串的substring
就是直接截取前后子字符串拼接即可:
class Solution {
public String reverseLeftWords(String s, int n) {
return s.substring(n,s.length())+s.substring(0,n);
}
}
2.通過StringBuilder
使用可變字符串來編輯,先把整個字符串反轉(zhuǎn),再把兩段分別反轉(zhuǎn)就是答案了:
class Solution {
public String reverseLeftWords(String s, int n) {
StringBuilder ns=new StringBuilder(s);
reverseString(ns,0,s.length()-1);
reverseString(ns,0,s.length()-n-1);
reverseString(ns,s.length()-n,s.length()-1);
return ns.toString();
}
private static void reverseString(StringBuilder ns, int i, int length) {
while (i<length){
char tem= ns.charAt(i);
ns.setCharAt(i,ns.charAt(length));
ns.setCharAt(length,tem);
i++;length--;
}
}
}
3.使用字符數(shù)組
創(chuàng)建等長的字符串?dāng)?shù)組,從旋轉(zhuǎn)的點開始向后填進數(shù)組,到最后的位置返回到字符串第一個(取余吧),直到n個字符結(jié)束。
class Solution {
public String reverseLeftWords(String s, int n) {
char[]ns=new char[s.length()];
for (int i = 0; i < s.length(); i++) {
ns[i]=s.charAt((i+n)%s.length());
}
return new String(ns);
}
}
返回第一頁。?
?物有本末,事有終始,知所先后。??
文章來源:http://www.zghlxwxcb.cn/news/detail-430584.html
???????我的CSDN???????? 文章來源地址http://www.zghlxwxcb.cn/news/detail-430584.html
到了這里,關(guān)于LeetCode:劍指 Offer 58 - II. 左旋轉(zhuǎn)字符串的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!