ChatGPT brush force buckle interview questions 01.09. String rotation (for string matching search and judgment to enhance password complexity)

topic description

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

示例1:

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

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

字符串长度在[0, 100000]范围内。
说明:

你能只调用一次检查子串的方法吗?

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

Start solving problems (kotlin)

The Kotlin code is implemented as follows:

fun isFlipedString(s1: String, s2: String): Boolean {
    if (s1.length != s2.length) {
        return false
    }
    val s1s1 = s1 + s1
    return s1s1.contains(s2)
}

// 测试示例
fun main() {
    val s1 = "waterbottle"
    val s2 = "erbottlewat"
    println(isFlipedString(s1, s2))  // 输出:true
    
    val s3 = "aa"
    val s4 = "aba"
    println(isFlipedString(s3, s4))  // 输出:false
}

In this example, we define a isFlipedStringfunction to determine s2whether it is s1a rotated string. We first judge s1whether s2the lengths of the sums are equal, and return directly if they are not equal false. Then, we will s1splice it with itself s1s1, and then s1s1.contains(s2)judge s2whether it is s1s1a substring, if it is, return it true, otherwise return it false. In mainthe function, we tested two examples and the output was as expected.

practical application

This function can be used to determine whether a string is the rotation result of another string. The actual application scenarios are as follows:

  1. Determine whether the password is a rotation result: In some cases, the user may rotate the password when entering it, such as rotating "password" into "dpassword". This function can be used to check whether the password entered by the user is a rotation result of the original password to increase the complexity and security of the password.
  2. Determine whether a string is the result of a cyclic shift: In cryptography and coding, a cyclic shift is a common operation that cyclically shifts the characters of a string to the right or to the left. Use this function to determine whether a string is the result of another string after a circular shift operation.
  3. String Matching and Searching: In some cases, we need to search a string within another string. If we know that the target string is a rotated result of the original string, we can use this function to see if the string matches or contains the rotated result.

In short, this function can be used in various scenarios where it is necessary to determine whether a string is the rotation result of another string, and it can provide the convenience of string processing and matching.

Guess you like

Origin blog.csdn.net/qq_39154376/article/details/131842702