NOTE

Reverse String

A Go implementation for reversing a string.

Data Structures & AlgorithmsCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. Problem Description

Write a program that accepts a string and outputs the reversed string. (The string length does not exceed 1000.)

2. Approach

3. Implementation

package main

/**
 * Reverse string
 * @param str string
 * @return string
 */
func solve(str string) string {
	if str == "" {
		return str
	}

	return reverse(str)
}

func reverse(str string) string {
	runes := []rune(str)
	i, j := 0, len(runes)-1
	for i < j {
		runes[i], runes[j] = runes[j], runes[i]
		i++
		j--
	}
	return string(runes)
}

4. References

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub