[LeetCode] 2000. Reverse Prefix of Word
Given a0-indexedstringword
and a characterch
,reversethe segment ofword
that starts at index0
and ends at the index of thefirst occurrenceofch
(inclusive). If the characterch
does not exist inword
, do nothing.
- For example, if
word = "abcdefd"
andch = "d"
, then you shouldreversethe segment that starts at0
and ends at3
"dcbaefd"
.
Returnthe resulting string.
Example 1:
Input: word = "abcdefd", ch = "d" Output: "dcbaefd" Explanation:The first occurrence of "d" is at index 3. Reverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd".
Example 2:
Input: word = "xyxzxe", ch = "z" Output: "zxyxxe" Explanation:The first and only occurrence of "z" is at index 3. Reverse the part of word from 0 to 3 (inclusive), the resulting string is "zxyxxe".
Example 3:
Input: word = "abcd", ch = "z" Output: "abcd" Explanation:"z" does not exist in word. You should not do any reverse operation, the resulting string is "abcd".
Constraints:
1 <= word.length <= 250
word
consists of lowercase English letters.ch
is a lowercase English letter.
反轉單詞字首。
給你一個下標從 0 開始的字串 word 和一個字元 ch 。找出 ch 第一次出現的下標 i ,反轉 word 中從下標 0 開始、直到下標 i 結束(含下標 i )的那段字元。如果 word 中不存在字元 ch ,則無需進行任何操作。
例如,如果 word = "abcdefd" 且 ch = "d" ,那麼你應該 反轉 從下標 0 開始、直到下標 3 結束(含下標 3 )。結果字串將會是 "dcbaefd" 。
返回 結果字串 。來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/reverse-prefix-of-word
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
題意不難理解,反轉 input 字串的某一個字首,返回反轉之後的結果。需要考慮的 corner case 是如果字串中不存在目標字母,則返回原字串。一般的 case 是如果找到了目標字母第一次出現的位置 i,則對這個字首 (0, i) 進行反轉,與字串剩餘的部分拼接好之後返回即可。
時間O(n)
空間O(n) - StringBuilder
Java實現
1 class Solution { 2 public String reversePrefix(String word, char ch) { 3 // corner case 4 if (!word.contains(ch + "")) { 5 return word; 6 } 7 8 // normal case 9 StringBuilder sb = new StringBuilder(); 10 int i = 0; 11 while (i < word.length()) { 12 if (word.charAt(i) == ch) { 13 sb.append(helper(word, 0, i)); 14 break; 15 } 16 i++; 17 } 18 i++; 19 20 while (i < word.length()) { 21 sb.append(word.charAt(i)); 22 i++; 23 } 24 return sb.toString(); 25 } 26 27 private String helper(String word, int start, int end) { 28 char[] w = word.substring(start, end + 1).toCharArray(); 29 while (start < end) { 30 char temp = w[start]; 31 w[start] = w[end]; 32 w[end] = temp; 33 start++; 34 end--; 35 } 36 StringBuilder sb = new StringBuilder(); 37 for (char c : w) { 38 sb.append(c); 39 } 40 return sb.toString(); 41 } 42 }