Home > Backend Development > C++ > body text

## Is String s2 a Rotated Version of String s1?

Mary-Kate Olsen
Release: 2024-10-25 07:12:29
Original
176 people have browsed it

## Is String s2 a Rotated Version of String s1?

Interview Question: Identifying String Rotation

Given two strings, s1 and s2, an interviewee recently faced a question on determining whether s1 is a rotated version of s2. A rotated version refers to a string where its characters have been shifted a certain number of positions to the left or right, resulting in a new string that contains the same characters in a different order.

Simplified Solution

To solve this problem, a simple yet effective approach can be employed. Before proceeding, it is essential to verify that both strings, s1 and s2, have the same length. Once this is confirmed, we can concatenate s1 with itself to form a longer string, denoted as s1s1.

Now, the crux of the solution lies in examining whether s2 is a substring of the concatenated string s1s1. If s2 is indeed a substring of s1s1, this indicates that the characters of s2 can be found within a contiguous segment of s1s1. Consequently, a rotation of s1, which essentially shifts its characters, would result in a new string that retains s2 as a substring.

Example

Consider the strings s1 = "stackoverflow" and s2 = "tackoverflows". By concatenating s1 with itself, we obtain the string s1s1 = "stackoverflowstackoverflow". Notice that s2 is a substring of s1s1, signifying that s1 and s2 are rotated versions of each other.

This simplified solution harnesses the powerful capabilities of substring search algorithms, offering an efficient way to determine string rotation. By avoiding excessive looping or manipulation, it provides a concise and elegant approach to solving the problem.

The above is the detailed content of ## Is String s2 a Rotated Version of String s1?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!