Quantcast
Channel: Coddicted
Viewing all articles
Browse latest Browse all 10

Solved! Leetcode 2000. Reverse Prefix of Word

$
0
0

Description: Reverse Prefix of Word

Given a 0-indexed string word and a character chreverse 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.

  • For example, if word = "abcdefd" and ch = "d", then you should reverse the segment that starts at 0 and ends at 3 (inclusive). The resulting string will be "dcbaefd".

Return the resulting string.

Example 1

<strong>Input:</strong> word = "abcdefd", ch = "d"
<strong>Output:</strong> "dcbaefd"
<strong>Explanation:</strong>&nbsp;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

<strong>Input:</strong> word = "xyxzxe", ch = "z"
<strong>Output:</strong> "zxyxxe"
<strong>Explanation:</strong>&nbsp;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

<strong>Input:</strong> word = "abcd", ch = "z"
<strong>Output:</strong> "abcd"
<strong>Explanation:</strong>&nbsp;"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.

Solution

class Solution {
    public String reversePrefix(String word, char ch) {
        if(word==null || word.isBlank()){
            return word;
        }

        //find the first index of ch in the word
        int end = word.indexOf(ch);
        if(end!=-1){
            char&#91;] c = word.toCharArray();
            int left = 0;
            int right = end;

            //reverse the portion between 0 and the index of ch
            while(left&lt;right){
                char t = c&#91;left];
                c&#91;left] = c&#91;right];
                c&#91;right] = t;
                left++;
                right--;
            }
            word = new String(c);
        }
        return word;
    }
}

Time Complexity

O(n), where n is the number of characters in the word (specifically O(n/2))

Space Complexity

O(n), where n is the number of characters in the word

Rate this post


Viewing all articles
Browse latest Browse all 10

Trending Articles