Home > Backend Development > C++ > body text

Is a String a Rotation of Another? A Simple Approach in Java.

Mary-Kate Olsen
Release: 2024-10-25 01:56:30
Original
567 people have browsed it

Is a String a Rotation of Another? A Simple Approach in Java.

How to Determine if One String Is a Rotation of Another

In software interviews, candidates may encounter intriguing questions like this: given two strings s1 and s2, how do you ascertain whether s1 is a rotated variant of s2?

A string is rotated when it's been split at a pivot point and the two halves are reattached in reverse order. For instance, "stackoverflow" could be rotated to become "tackoverflows" or "ackoverflowst".

One possible solution, proposed by the interviewee, involves finding the longest prefix of s2 that is a substring of s1. This identifies the rotation point. Once found, s2 can be divided into two substrings and checked if their concatenation equals s1.

However, the interviewer requested a simpler solution. Consider the following approach:

  • Ensure s1 and s2 have the same length.
  • Verify if s2 exists as a substring within s1, which is achieved by concatenating s1 with itself and searching for s2.

In Java, this method can be implemented as follows:

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

By using string concatenation and searching, this solution efficiently determines if one string is a rotated version of another.

The above is the detailed content of Is a String a Rotation of Another? A Simple Approach in Java.. 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!