刷题-力扣-面试题 01.09. 字符串轮转(Brush questions – force buckle – interview question 01.09 String rotation)

题目链接

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/string-rotation-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目描述

字符串轮转。给定两个字符串s1和s2,请编写代码检查s2是否为s1旋转而成(比如,waterbottle是erbottlewat旋转后的字符串)。

示例1:

 输入:s1 = "waterbottle", s2 = "erbottlewat"
 输出:True

示例2:

 输入:s1 = "aa", s2 = "aba"
 输出:False

提示:

  • 字符串长度在[0, 100000]范围内。
    说明:
  • 你能只调用一次检查子串的方法吗?

题目分析

  • 根据题目描述,若s2是s1旋转的到,那么s1也可由s2旋转得到
  • 若在旋转的位置将字符串分为两部分,s1的前半部分对应s2后半部分;s1的后半部分对应s2的前半部分
  • 当两个s1首尾拼接后就会包含s2

代码

class Solution {
public:
    bool isFlipedString(string s1, string s2) {
        if (s1.length() != s2.length()) { return false; }
        std::string s12 = s1 + s1;
        return s12.find(s2) == std::string::npos ? false : true;
    }
};
————————

Title Link

Source: leetcode
Link: https://leetcode-cn.com/problems/string-rotation-lcci
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

Title Description

String rotation. Given the two strings S1 and S2, write code to check whether S2 is rotated by S1 (for example, waterbottle is the string rotated by erbottlewat).

Example 1:

 输入:s1 = "waterbottle", s2 = "erbottlewat"
 输出:True

Example 2:

 输入:s1 = "aa", s2 = "aba"
 输出:False

Tips:

  • The string length is in the range of [0, 100000].
    explain:
  • Can you call the method of checking substring only once?

Topic analysis

  • According to the title description, if S2 is rotated by S1, S1 can also be obtained by S2 rotation
  • If the string is divided into two parts at the rotating position, the first half of S1 corresponds to the second half of S2; The second half of S1 corresponds to the first half of S2
  • When two S1 ends are spliced, S2 will be included

code

class Solution {
public:
    bool isFlipedString(string s1, string s2) {
        if (s1.length() != s2.length()) { return false; }
        std::string s12 = s1 + s1;
        return s12.find(s2) == std::string::npos ? false : true;
    }
};