NOTE

Check Palindrome

Check whether a string is a palindrome using reversal and two pointers.

Data Structures & AlgorithmsCreated Updated 1 min readhistorical

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

1. Problem Description

Given a string, write a function to determine whether it is a palindrome. Return true if it is, otherwise return false.

2. Approach

  • Reverse
  • Two pointers

3. Implementation

3.1. Reverse

func judge(str string) bool {
	return str == reverse2(str)
}

func reverse2(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)
}

3.2. Two Pointers

func judge( s string ) bool {
    left := 0
    right := len(s)-1
    for left < right {
        if s[left] != s[right] {
            return false
        }
        left++
        right--
    }
    return true
}

4. References

Discussion

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