返回介绍

lcci / 01.09.String Rotation / README_EN

发布于 2024-06-17 01:04:43 字数 3021 浏览 0 评论 0 收藏 0

01.09. String Rotation

中文文档

Description

Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 (e.g.,"waterbottle" is a rotation of"erbottlewat"). Can you use only one call to the method that checks if one word is a substring of another?

Example 1:


Input: s1 = "waterbottle", s2 = "erbottlewat"

Output: True

Example 2:


Input: s1 = "aa", "aba"

Output: False

 

Note:

  1. 0 <= s1.length, s1.length <= 100000

Solutions

Solution 1: String Matching

First, if the lengths of strings $s1$ and $s2$ are not equal, they are definitely not rotation strings of each other.

Second, if the lengths of strings $s1$ and $s2$ are equal, then by concatenating two $s1$ together, the resulting string $s1 + s1$ will definitely include all rotation cases of $s1$. At this point, we just need to check whether $s2$ is a substring of $s1 + s1$.

# True
s1 = "aba"
s2 = "baa"
s1 + s1 = "abaaba"
      ^^^

# False
s1 = "aba"
s2 = "bab"
s1 + s1 = "abaaba"

The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of string $s1$.

class Solution:
  def isFlipedString(self, s1: str, s2: str) -> bool:
    return len(s1) == len(s2) and s2 in s1 * 2
class Solution {
  public boolean isFlipedString(String s1, String s2) {
    return s1.length() == s2.length() && (s1 + s1).contains(s2);
  }
}
class Solution {
public:
  bool isFlipedString(string s1, string s2) {
    return s1.size() == s2.size() && (s1 + s1).find(s2) != string::npos;
  }
};
func isFlipedString(s1 string, s2 string) bool {
  return len(s1) == len(s2) && strings.Contains(s1+s1, s2)
}
function isFlipedString(s1: string, s2: string): boolean {
  return s1.length === s2.length && (s2 + s2).indexOf(s1) !== -1;
}
impl Solution {
  pub fn is_fliped_string(s1: String, s2: String) -> bool {
    s1.len() == s2.len() && (s2.clone() + &s2).contains(&s1)
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文