当前位置: 面试刷题>> 用isSubstring判断字符串的循环移动 (经典算法题500道)


题目描述补充

题目:给定两个字符串s1s2,其中s2可能是s1的一个循环移动(即将s1的某个前缀移动到尾部得到的字符串)。请编写一个函数isSubstringRotation来判断s2是否是s1的循环移动。

例如:

  • s1 = "waterbottle"
  • s2 = "erbottlewat"
  • 在这个例子中,s2s1的循环移动(将"water"移动到尾部),所以isSubstringRotation(s1, s2)应该返回true

PHP 代码示例

function isSubstringRotation($s1, $s2) {
    if (strlen($s1) !== strlen($s2)) {
        return false; // 如果两个字符串长度不同,直接返回false
    }
    
    $s1s1 = $s1 . $s1; // 将s1拼接自己,如果s2是s1的循环移动,s2必定是s1s1的子串
    
    return strpos($s1s1, $s2) !== false; // 使用strpos查找s2是否是s1s1的子串
}

// 测试示例
$s1 = "waterbottle";
$s2 = "erbottlewat";
echo isSubstringRotation($s1, $s2) ? "true" : "false"; // 输出 true

Python 代码示例

def isSubstringRotation(s1, s2):
    if len(s1) != len(s2):
        return False  # 如果两个字符串长度不同,直接返回False
    
    s1s1 = s1 + s1  # 将s1拼接自己
    
    return s2 in s1s1  # 判断s2是否是s1s1的子串

# 测试示例
s1 = "waterbottle"
s2 = "erbottlewat"
print(isSubstringRotation(s1, s2))  # 输出 True

JavaScript 代码示例

function isSubstringRotation(s1, s2) {
    if (s1.length !== s2.length) {
        return false; // 如果两个字符串长度不同,直接返回false
    }
    
    const s1s1 = s1 + s1; // 将s1拼接自己
    
    return s1s1.includes(s2); // 判断s2是否是s1s1的子串
}

// 测试示例
const s1 = "waterbottle";
const s2 = "erbottlewat";
console.log(isSubstringRotation(s1, s2)); // 输出 true

码小课网站中有更多关于字符串处理、算法和数据结构的相关内容分享,欢迎大家学习交流。

推荐面试题