상세 컨텐츠

본문 제목

[Go] Array and string - Reverse String

Go/Leet Code

by Gopythor 2022. 4. 9. 18:27

본문

728x90
반응형

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.

 

Example 1:

Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

Example 2:

Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]

 

Constraints:

My code(sample 6600 KB submission)

func reverseString(s []byte) {
	for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
		s[i], s[j] = s[j], s[i]
	}
}
  • I think this time problem is so easy to solve.
  • for loop can have two variables like upper.
  • they cannot have increment, decrement but they can have normal addition and subtraction

https://go.dev/play/p/qcDKdMx9uIq

 

Go Playground - The Go Programming Language

About the Playground The Go Playground is a web service that runs on go.dev's servers. The service receives a Go program, vets, compiles, links, and runs the program inside a sandbox, then returns the output. If the program contains tests or examples and n

go.dev

 

 

sample 15 ms submission & sample 6500 KB submission

func reverseString(s []byte)  {
	for i:=0 ; i<len(s)/2; i++ {
		s[i], s[len(s)-1-i] = s[len(s)-1-i], s[i]
	}
}

sample 20 ms submission

func reverseString(s []byte)  {
    i, j := 0, len(s) - 1
    
    for i < j {
        s[i], s[j] = s[j], s[i]
        
        i++
        j--
    }
}

sample 22 ms submission

func reverseString(s []byte)  {
    var temp byte
    for i:=0;i<len(s)/2;i++ {
        temp = s[i]
            s[i] = s[len(s) - i - 1]
            s[len(s) - i - 1] = temp
        
    }
    
}

sample 23 ms submission

func reverseString(s []byte)  {
    
    v := len(s)/2
    
    for i := 0; i < v; i++ {
        tmp := s[i]
        s[i] = s[len(s)-1-i]
        s[len(s)-1-i] = tmp
    }
}

sample 24 ms submission

func reverseString(str []byte)  {
	size := len(str)
	for i := 0; i < size / 2; i++ {
		tpr := str[i]
		str[i] = str[size - 1 - i]
		str[size - 1 - i] = tpr
	}
}

sample 6400 KB submission

func reverseString(s []byte)  {
    var first, last int = 0, len(s) - 1
    for ; first < last; {
        s[first], s[last] = s[last], s[first]
        first++
        last--
    }
}

sample 6700 KB submission

func reverseString(s []byte)  {
    for i:=0; i<len(s)/2; i++ {
        j := len(s)-i-1
        temp := s[i]
        s[i] = s[j]
        s[j] = temp
    }
}
728x90
반응형

관련글 더보기

댓글 영역