-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Expand file tree
/
Copy pathis_rotated.py
More file actions
62 lines (47 loc) · 1.51 KB
/
is_rotated.py
File metadata and controls
62 lines (47 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
"""
Is Rotated String
Given two strings, determine if the second is a rotated version of the first.
Two approaches are provided: concatenation check and brute force.
Reference: https://leetcode.com/problems/rotate-string/
Complexity:
Time: O(n) for concatenation approach, O(n^2) for brute force
Space: O(n)
"""
from __future__ import annotations
def is_rotated(first: str, second: str) -> bool:
"""Check if second is a rotation of first using string concatenation.
Args:
first: The original string.
second: The string to check as a rotation.
Returns:
True if second is a rotation of first, False otherwise.
Examples:
>>> is_rotated("hello", "llohe")
True
"""
if len(first) == len(second):
return second in first + first
else:
return False
def is_rotated_v1(first: str, second: str) -> bool:
"""Check if second is a rotation of first using brute force comparison.
Args:
first: The original string.
second: The string to check as a rotation.
Returns:
True if second is a rotation of first, False otherwise.
Examples:
>>> is_rotated_v1("hello", "llohe")
True
"""
if len(first) != len(second):
return False
if len(first) == 0:
return True
for offset in range(len(first)):
if all(
first[(offset + index) % len(first)] == second[index]
for index in range(len(first))
):
return True
return False