557. 反轉字串中的單詞 III(邏輯)1
阿新 • • 發佈:2020-12-15
技術標籤:LeetCode
給定一個字串,你需要反轉字串中每個單詞的字元順序,同時仍保留空格和單詞的初始順序。
示例:
輸入:"Let's take LeetCode contest"
輸出:"s'teL ekat edoCteeL tsetnoc"
解法一:邏輯
class Solution { public String reverseWords(String s) { char[] c = s.toCharArray(); int start = 0, end = 0; for(; end < c.length; end++){ if(c[end] == ' '){ reverse(c, start, end-1); start = end+1; } } reverse(c, start, end-1); return new String(c); } private void reverse(char[] c, int start, int end){ while(start < end){ char tmp = c[end]; c[end] = c[start]; c[start] = tmp; start++; end--; } } }