Rotate String Problem


Description

LeetCode Problem 796.

Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s.

A shift on s consists of moving the leftmost character of s to the rightmost position.

  • For example, if s = “abcde”, then it will be “bcdea” after one shift.

Example 1:

1
2
Input: s = "abcde", goal = "cdeab"
Output: true

Example 2:

1
2
Input: s = "abcde", goal = "abced"
Output: false

Constraints:

  • 1 <= s.length, goal.length <= 100
  • s and goal consist of lowercase English letters.


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
    bool rotateString(string A, string B) {
        if (A.size() != B.size())
            return false;
        if (A == B)      
            //for empty strings
            return true;
        
        int len = B.size();
        while (len--) {
            if (A == B)
                return true;
            // one shift on A
            A = A.substr(1) + A[0];     
        }
        return false;
    }
};




Related Posts

String Without Aaa Or Bbb Problem

LeetCode 984. Given two integers a and b, return any...

Shifting Letters Problem

LeetCode 848. You are given a string s of lowercase...

Positions Of Large Groups Problem

LeetCode 830. In a string sof lowercase letters, these letters...

Orderly Queue Problem

LeetCode 899. You are given a string s and an...

Number Of Lines To Write String Problem

LeetCode 806. You are given a string s of lowercase...

Masking Personal Information Problem

LeetCode 831. You are given a personal information string s,...