Home >Backend Development >C++ >## How Can String Concatenation Efficiently Determine String Rotation?

## How Can String Concatenation Efficiently Determine String Rotation?

Barbara Streisand
Barbara StreisandOriginal
2024-10-24 18:32:15760browse

## How Can String Concatenation Efficiently Determine String Rotation?

Determining String Rotation Using String Concatenation

A challenge commonly encountered in programming interviews involves verifying if one string is a rotated version of another. Given two strings s1 and s2, the task is to efficiently check if one is simply a cyclic permutation of the other.

In this instance, the candidate provided a solution that involves identifying the point of rotation and breaking s2 into two segments, s2a and s2b. By concatenating these segments and comparing the result to s1, the rotation can be confirmed.

However, the interviewer expressed a preference for a more straightforward approach. Here's a simpler solution using string concatenation and string searching:

Java Implementation:

<code class="java">public static boolean isRotation(String s1, String s2) {
    return (s1.length() == s2.length()) && ((s1 + s1).indexOf(s2) != -1);
}</code>

Python Implementation:

<code class="python">def is_rotation(s1, s2):
    return len(s1) == len(s2) and s2 in s1 * 2</code>

In this solution, we first ensure that both strings are of equal length. Then, we concatenate s1 with itself, effectively creating a string that contains both the original string and its rotated version. By checking whether s2 exists within this concatenated string, we can determine if one is a rotation of the other.

The above is the detailed content of ## How Can String Concatenation Efficiently Determine String Rotation?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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