Check if a string is rotation of another WITHOUT concatenating

后端 未结 11 1415
死守一世寂寞
死守一世寂寞 2020-12-25 08:11

There are 2 strings , how can we check if one is a rotated version of another ?

For Example : hello --- lohel

One simple solution is by co

11条回答
  •  臣服心动
    2020-12-25 09:05

    There's no need to concatenate at all.

    First, check the lengths. If they're different then return false.

    Second, use an index that increments from the first character to the last of the source. Check if the destination starts with all the letters from the index to the end, and ends with all the letters before the index. If at any time this is true, return true.

    Otherwise, return false.

    EDIT:

    An implementation in Python:

    def isrot(src, dest):
      # Make sure they have the same size
      if len(src) != len(dest):
        return False
    
      # Rotate through the letters in src
      for ix in range(len(src)):
        # Compare the end of src with the beginning of dest
        # and the beginning of src with the end of dest
        if dest.startswith(src[ix:]) and dest.endswith(src[:ix]):
          return True
    
      return False
    
    print isrot('hello', 'lohel')
    print isrot('hello', 'lohell')
    print isrot('hello', 'hello')
    print isrot('hello', 'lohe')
    

提交回复
热议问题