Given two strings A and B, return whether or not A can be shifted some number of times to get B.
For example, if A is abcde
and B is cdeab
, return true. If A is abc
and B is acb
, return false.
Example:
Input: str1 = "abcde", str2 = "cdeab"
Output: true
Approach
C++
#include <bits/stdc++.h>using namespace std;bool isSameAfterShifting(string str1, string str2){// check if the strings are empty//or has different lengthsif (str1.size() == 0 || str2.size() == 0 ||str1.size() != str2.size())return false;// check if the strings are the sameif (str1 == str2)return true;// generate the arrayvector<string> arr;for (int i = 0; i < str1.size(); i++){string c = str1.substr(i) + str1.substr(0, i);arr.push_back(c);}for (int i = 0; i < arr.size(); i++){if (arr[i] == str2)return true;}return false;}int main(){string str1 = "abcde";string str2 = "cdeab";if (isSameAfterShifting(str1, str2))cout << "true";elsecout << "false";return 0;}
No comments:
Post a Comment