Skip to content

2000. Reverse Prefix of Word 👍

  • Time: $O(n)$
  • Space: $O(n)$
1
2
3
4
5
6
7
class Solution {
 public:
  string reversePrefix(string word, char ch) {
    reverse(word.begin(), word.begin() + word.find(ch) + 1);
    return word;
  }
};
1
2
3
4
5
6
7
8
9
class Solution {
  public String reversePrefix(String word, char ch) {
    final int i = word.indexOf(ch) + 1;
    return new StringBuilder(word.substring(0, i)) //
        .reverse()                                 //
        .append(word.substring(i))                 //
        .toString();
  }
}
1
2
3
4
class Solution:
  def reversePrefix(self, word: str, ch: str) -> str:
    i = word.find(ch) + 1
    return word[:i][::-1] + word[i:]