การหมุนสตริงซ้าย n ครั้ง (n = ความยาวสตริง)
สร้างรายการของสตริงที่หมุนซ้าย 1, 2, ..., n ตำแหน่ง
อัลกอริทึม
- res = [], n = len(s)
- วน i = 0 ถึง n-1:
- s = s[1:] + s[0] (หมุนซ้าย 1 ตำแหน่ง)
- เพิ่ม s ลง res
- คืนค่า res
ตัวอย่างโค้ด
def solve(s):
res = []
n = len(s)
for i in range(0, n):
s = s[1:n] + s[0]
res.append(s)
return res
s = "hello"
print(solve(s))
ผลลัพธ์
['elloh', 'llohe', 'lohel', 'ohell', 'hello']
คำอธิบาย
"hello" → "elloh" → "llohe" → "lohel" → "ohell" → "hello" (กลับมาที่เดิมหลังหมุน 5 ครั้ง)