其他分享
首页 > 其他分享> > [LeetCode] 2000. Reverse Prefix of Word

[LeetCode] 2000. Reverse Prefix of Word

作者:互联网

Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing.

Return the 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:

反转单词前缀。

给你一个下标从 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 }

 

LeetCode 题目总结

标签:下标,ch,word,string,end,Prefix,2000,sb,Word
来源: https://www.cnblogs.com/cnoodle/p/15865240.html