LeetCode 796: Rotate String Solution

Master LeetCode problem 796 (Rotate String), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

796. Rotate String

Problem Explanation

Explanation

To solve this problem, we can concatenate the string s with itself, and then check if goal is a substring of the concatenated string. If goal is a substring of the concatenated string, then s can be rotated to become goal.

Algorithm:

  1. Concatenate s with itself to form a new string newStr.
  2. Check if goal is a substring of newStr.
  3. If goal is a substring, return true. Otherwise, return false.

Time Complexity: O(n), where n is the length of the string s. Space Complexity: O(n), to store the concatenated string newStr.

Solution Code

class Solution {
    public boolean rotateString(String s, String goal) {
        if (s.length() != goal.length()) {
            return false;
        }
        String newStr = s + s;
        return newStr.contains(goal);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 796 (Rotate String)?

This page provides optimized solutions for LeetCode problem 796 (Rotate String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 796 (Rotate String)?

The time complexity for LeetCode 796 (Rotate String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 796 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 796 in Java, C++, or Python.

Back to LeetCode Solutions