Leetcode 344 Reverse String, Leetcode 541 Reverse StringII

344. Reverse String #

Write a function that reverses a string. The input string is given as an array of characters s. You must do this by modifying the input array in-place with O(1) extra memory.

Answer:

func reverseString(s []byte)  {
    n:=len(s)
    i,j:=0,n-1
    for i<j {
        s[i],s[j]=s[j],s[i]
        i++
        j--
    }
}
  • I have learnt that:
    • we do not need extra edge cases for reverse string

541. Reverse String II #

Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.

If there are fewer than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and leave the other as original.

  • I have learnt that:
    • we can increase 2k every iteration
    • we need to transform string into []byte to edit and then transform it back to return as string
    • for tail cases, we have 2 scenarios to deal with
func reverseStr(s string, k int) string {
  ss := []byte(s)
  n := len(s)
  for i:=0;i<n;i+=2*k{
     if i + k<=n {
        reverse(ss[i:i+k])
     }else{
        reverse(ss[i:n])
     }
  }
  return string(ss)
}

func reverse(b []byte) {
    left := 0
    right := len(b) - 1
    for left < right {
        b[left], b[right] = b[right], b[left]
        left++
        right--
    }
}