Strings
Loading
Loading
Strings
Symmetry as a property of a centre, and a distinction that changes which pattern applies.
By the end of this chapter
This distinction decides which techniques are even available, so it is worth being precise about.
| Term | Meaning | Count in a string of length n |
|---|---|---|
| Substring | Contiguous run of characters | n(n+1)/2 |
| Subsequence | Characters in order, gaps allowed | 2ⁿ |
def is_symmetric(text): left, right = 0, len(text) - 1 while left < right: if text[left] != text[right]: return False left += 1 right -= 1 return TrueGenerating every substring and testing each is O(n³). But symmetry is a property of a centre, not of a substring — so generate centres instead and grow outward.
"ABCBA"centre at CB…B matchesexpandA…A matchesexpandout of bounds — stop, length 5the whole stringdef longest_symmetric(text): best_start, best_len = 0, 1 def expand(left, right): nonlocal best_start, best_len while left >= 0 and right < len(text) and text[left] == text[right]: left -= 1 right += 1 length = right - left - 1 # the loop overshoots by one each side if length > best_len: best_len, best_start = length, left + 1 for i in range(len(text)): expand(i, i) # odd-length centre expand(i, i + 1) # even-length centre return text[best_start:best_start + best_len]Quick quiz
Sign in to keep a note here. It is free, and nobody else can see it.
Sign inWhat this chapter was for:
Before moving on: take the quiz above, and try 2 practice problems.