Check if String is Rotation of Another
C++
Hard
6 views
Problem Description
Check if str2 is rotation of str1. Example: "abcd" -> "cdab".
Real Life: Circular string matching.
Step-by-Step Logic:
1. Check if lengths are equal
2. Concatenate str1 with itself
3. Check if str2 is substring of concatenated string
4. If yes, str2 is rotation of str1
Official Solution
void string_q13_rotation_check() {
string str1 = "abcde";
string str2 = "cdeab";
if(str1.length() != str2.length()) {
cout << "NOT a rotation (different lengths)" << endl;
return;
}
string concatenated = str1 + str1;
bool isRotation = false;
// Check if str2 is substring of concatenated
for(int i = 0; i <= concatenated.length() - str2.length(); i++) {
bool match = true;
for(int j = 0; j < str2.length(); j++) {
if(concatenated[i + j] != str2[j]) {
match = false;
break;
}
}
if(match) {
isRotation = true;
break;
}
}
if(isRotation) {
cout << str2 << " is a ROTATION of " << str1 << endl;
} else {
cout << str2 << " is NOT a rotation of " << str1 << endl;
}
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!