leetcode 796. Rotate String(python)

【摘要】 描述
We are given two strings, A and B.
A shift on A consists of taking string A and moving the leftmost character to the rightmost position. For example, if A = ‘abcde’, then it will be…

描述

We are given two strings, A and B.

A shift on A consists of taking string A and moving the leftmost character to the rightmost position. For example, if A = ‘abcde’, then it will be ‘bcdea’ after one shift on A. Return True if and only if A can become B after some number of shifts on A.

Example 1:

Input: A = 'abcde', B = 'cdeab'
Output: true	

  
 

Example 2:

Input: A = 'abcde', B = 'abced'
Output: false

  
 

Note:

A and B will have length at most 100.

  
 

解析

根据题意,就是判断在经过了 shift 操作之后的 A 和 B 是否相等,先判断其中出现的字符和数量是否相等,如果相等则对 A 进行 len(A) 次的 shift 操作,每次操作判断其与 B 是否相等,如果相等则返回 True, 如果遍历 len(A) 次之后仍不相等,则返回 False 。

解答

class Solution(object): def rotateString(self, A, B): """ :type A: str :type B: str :rtype: bool """ a = collections.Counter(A) b = collections.Counter(B) if a != b: return False n = len(A) while n >= 0: if A == B: return True else: n -= 1 A = A[1:]+A[0] return False 
  
 

运行结果

Runtime: 16 ms, faster than 78.91% of Python online submissions for Rotate String.
Memory Usage: 13.7 MB, less than 10.19% of Python online submissions for Rotate String.

  
 

原题链接:https://leetcode.com/problems/rotate-string/

您的支持是我最大的动力

文章来源: blog.csdn.net,作者:王大丫丫,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/wang7075202/article/details/115871339

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享