Rotate String
LeetCode 812 | Difficulty: Easyβ
EasyProblem Descriptionβ
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:
Input: s = "abcde", goal = "cdeab"
Output: true
Example 2:
Input: s = "abcde", goal = "abced"
Output: false
Constraints:
- `1 <= s.length, goal.length <= 100`
- `s` and `goal` consist of lowercase English letters.
Topics: String, String Matching
Approachβ
String Processingβ
Consider character frequency counts, two-pointer approaches, or building strings efficiently. For pattern matching, think about KMP or rolling hash. For palindromes, expand from center or use DP.
When to use
Anagram detection, palindrome checking, string transformation, pattern matching.
Solutionsβ
Solution 1: C# (Best: 115 ms)β
| Metric | Value |
|---|---|
| Runtime | 115 ms |
| Memory | 35.7 MB |
| Date | 2022-01-21 |
Solution
public class Solution {
public bool RotateString(string s, string goal) {
return s.Length == goal.Length && (s+s).IndexOf(goal)>=0;
}
}
π 1 more C# submission(s)
Submission (2022-01-21) β 141 ms, 35.9 MBβ
public class Solution {
public bool RotateString(string s, string goal) {
return s.Length == goal.Length && (s+s).Contains(goal);
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Solution | $O(n)$ | $O(1) to O(n)$ |
Interview Tipsβ
Key Points
- Start by clarifying edge cases: empty input, single element, all duplicates.