Simple Java solution with detailed explanation


  • 0
    I

    Use StringBuilder Class methods:

    • StringBuilder reverse()
      This method causes this character sequence to be replaced by the reverse of the sequence.
    • StringBuilder replace(int start, int end, String str)
      This method replaces the characters in a substring of this sequence with characters in the specified String.
    • String substring(int start)
    • String substring(int start, int end)
      This method returns a new String that contains a subsequence of characters currently contained in this character sequence.
    • String toString()
      This method returns a string representing the data in this sequence.

    Notice :
    start This is the beginning index, inclusive.
    end This is the ending index, exclusive.

    public class Solution {
        public String reverseStr(String s, int k) {
            StringBuilder sb = new StringBuilder(s);
            int startIndex = 0;
            while(startIndex < s.length()) {
                if (startIndex + k <= s.length()) {
                    sb.replace(startIndex, startIndex + k, new StringBuilder(s.substring(startIndex, startIndex + k)).reverse().toString());
                } else {
                    sb.replace(startIndex, sb.length(), new StringBuilder(s.substring(startIndex)).reverse().toString());
                }
                startIndex += 2 * k;
            }
            
            return sb.toString();
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.