NOTE

Left Rotate String

Record two implementations of cyclic left rotation of a string: slicing and concatenation, and three reversals.

Data Structures & AlgorithmsCreated Updated 1 min readhistorical

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

1. Problem Description

Assembly language has a shift instruction called rotate left (ROL). This task uses a string to simulate its result. Given a character sequence S, output the sequence after cyclically rotating it K positions to the left. For example, for S = “abcXYZdef”, rotating left by 3 positions produces “XYZdefabc”. Simple enough? OK, get it done!

2. Approach

  • Reverse

3. Implementation

package main

/**
 * The class name, method name, and parameter names in the code have already been specified. Do not modify them; directly return the value required by the method.
 *
 * @param str string
 * @param n integer
 * @return string
 */
// Space: O(n)
// Time: O(n)
func LeftRotateString(str string, n int) string {
	if len(str) == 0 || n < 0 {
		return ""
	}

	n = n % len(str)
	res := str[n:] + str[:n]
	return res
}

// Space: O(n)
// Time: O(n)
func LeftRotateString2(str string, n int) string {
	if len(str) == 0 || n < 0 {
		return ""
	}

	n = n % len(str)

	//123abc
	runes := []rune(str)
	//321abc first reverse the first half
	reverse(runes, 0, n-1)
	//321cba then reverse the second half
	reverse(runes, n, len(str)-1)
	//abc123 finally reverse the whole string
	reverse(runes, 0, len(str)-1)

	return string(runes)
}

func reverse(runes []rune, i int, j int) {
	for i < j {
		runes[i], runes[j] = runes[j], runes[i]
		i++
		j--
	}
}

4. References

Discussion

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