算法 - 字符串 判断2个字符串是否互为旋转词

这个算法题,是来判断2个string字符串,是否互为旋转词

举例:a="cdab",b="abcd",返回true.a="1ab2",b="ab12”,返回fase,a="2ab1",b="ab12",返回true。

这道算法题的解题思路:

两个长度相等的字符串 A和 B 互为旋转词,‌当且仅当‌ B 是字符串 A+A 的子串。

即:len(A) == len(B) 且 (A + A).contains(B) 为真。


image

 

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------4

代码如下:

public class Solution
{
    public static bool IsRotateString(string a, string b)
    {
        // 长度不等直接返回false
        if (a.Length != b.Length)
        {
            return false;
        }
        string combine = a + a;
        // 判断b是否是combine的子串
        return combine.Contains(b);
    }

    public static void Main()
    {
        Console.WriteLine(IsRotateString("cdab", "abcd"));   // True
        Console.WriteLine(IsRotateString("1ab2", "ab12"));   // False
        Console.WriteLine(IsRotateString("2ab1", "ab12"));   // True
    }
}

 

posted on 2026-09-26 20:24  新西兰程序员  阅读(1)  评论(0)    收藏  举报