Problem of the Day
A new programming or logic puzzle every Mon-Fri

String Rotation

Given a string s1 and a string s2, write a function to return whether s2 is a rotation of s1 using only one call to strstr (or a similar function)? For example:

is_rotation(ABCD, CDAB) //return  true

is_rotation(ABCD, ACBD) //return false

Permalink: http://problemotd.com/problem/string-rotation/

Comments:

  • Anonymous - 9 years, 2 months ago

    I think I got it. Python 3

    def is_rotated(first, second):
        if len(first) != len(second):
            return False
        try:
            start = first.index(second[0])
        except ValueError:
            return False
        for i in range(start,  start + len(first)):
            if first[i % len(first)] != second[i-start]:
                return False
        return True
    

    reply permalink

  • Byron Mayne - 9 years, 1 month ago

    def is_rotation( value1, value2 ):
        if len(value1) != len(value2):
            return False
    
        length = len(value1) 
    
        for x in range(0, length):
            if value1[x] != value2[length - x - 1]:
                return false
    
        return True
    
    
    print(is_rotation("ABBC", "CBA"))
    print(is_rotation("ABC", "CBA"))
    

    reply permalink

Content curated by @MaxBurstein