技術分享:反轉字元串中的單詞
給定一個字元串,你需要反轉字元串中每個單詞的字元順序,同時仍保留空格和單詞的初始順序。
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
示例 1:
輸入: Let"s take LeetCode contest
輸出: s"teL ekat edoCteeL tsetnoc
注意:在字元串中,每個單詞由單個空格分隔,並且字元串中不會有任何額外的空格。
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
解題思路:
每次遇到空格字元,就把 從上一次空格字元開始到該空格字元止之間的所有字元反轉一下即可,只需要注意最後一個字元結束時,並不是空格字元,要再加一個判斷是否是已經索引到最後一位。
"abc def" 原字元串
["a" , "b" , "c" , " " , "d" , "e" ,"f"] 轉成char[]型數組
["c" , "b" , "a" , " "...] 遍曆數組,遇到第一個空格,把該空格到上個空格之間的字母反轉
[... " " , "d" , "e" ,"f"] 遍歷到最後一位,不是空格,依然要反轉到前一個空格間的字母
[... " " , "f" , "d" ,"e"] 反轉
"cba fde" 轉成字元串輸出
Java:
class Solution {
public String reverseWords(String s) {
int sLen = s.length(), k = 0, j = 0;//j記錄空格字元前的索引位置
char strs[] = s.toCharArray(), temp;//轉為字元數組
for (int i = 0; i sLen; i ) {
if (strs[i] == " ") j = i - 1;//遇到空格字元j值減1,為截取的字母段的最後一個字母的索引
else if (i == sLen - 1) j = i;//如果到最後一位,則j值不應該再減1
else continue;
for (; j = k; j--, k ) {//交換位置
temp = strs[j];
strs[j] = strs[k];
strs[k] = temp;
}
k = i 1;//k記錄空格字元後的索引位置
}
return String.valueOf(strs);
}
}
python不再復現上述定義指針解題的思路,這裡再次投機取巧,利用 python 切片特性及 split() 、join() 函數解題,解題思路:
"abc def gh" 原字元串
"hg fed cba" 切片特性反轉字元串
["hg" , "fed" , "cba"] split() 分割字元串
["cba" , "fed" , "hg"] 切片反轉數組
"cba fed hg" 拼接成字元串
Python3:
class Solution:
def reverseWords(self, s: str) - str:
return " ".join(s[::-1].split()[::-1])
※Kotlin技術分享-運算符重載
※推進微服務落地的 7 個步驟
TAG:千鋒JAVA開發學院 |