返回

旋转字符串!携手力扣,掌握字符串之精髓!

前端

力扣是一家致力于为全球开发者提供优质在线编程学习和交流平台的企业。其「字符串专题」汇集了众多精选题目,让学习者能够深入理解字符串操作的技巧和原理。其中,796. 旋转字符串是一道经典的题目,它要求学习者将一个给定的字符串进行旋转操作,并判断旋转后的字符串是否与原字符串相同。

这道题目的解决方法有多种,我们可以使用不同的编程语言和算法来实现。在本文中,我们将使用Python和Java两种语言分别实现这一算法。

Python实现:

def rotate_string(s, n):
    """
    Rotate a string by n positions to the right.

    Args:
        s: The string to be rotated.
        n: The number of positions to rotate the string by.

    Returns:
        The rotated string.
    """

    # Check if the string is empty.

    if not s:
        return s

    # Check if the number of positions to rotate is valid.

    n = n % len(s)

    # Rotate the string.

    return s[n:] + s[:n]


def is_rotated_string(s1, s2):
    """
    Check if two strings are rotated versions of each other.

    Args:
        s1: The first string.
        s2: The second string.

    Returns:
        True if the two strings are rotated versions of each other, False otherwise.
    """

    # Check if the two strings have the same length.

    if len(s1) != len(s2):
        return False

    # Check if the two strings are equal.

    if s1 == s2:
        return True

    # Rotate the second string and check if it is equal to the first string.

    for i in range(1, len(s1)):
        s2 = rotate_string(s2, 1)
        if s1 == s2:
            return True

    # The two strings are not rotated versions of each other.

    return False


if __name__ == "__main__":
    s1 = "hello"
    n = 2
    print(rotate_string(s1, n))  # Output: "lohel"

    s1 = "abcde"
    s2 = "cdeab"
    print(is_rotated_string(s1, s2))  # Output: True

Java实现:

public class RotateString {

    public static String rotateString(String s, int n) {
        if (s == null || s.length() == 0) {
            return s;
        }

        n = n % s.length();

        StringBuilder sb = new StringBuilder();
        sb.append(s.substring(n));
        sb.append(s.substring(0, n));

        return sb.toString();
    }

    public static boolean isRotatedString(String s1, String s2) {
        if (s1 == null || s2 == null || s1.length() != s2.length()) {
            return false;
        }

        String s1s1 = s1 + s1;

        return s1s1.contains(s2);
    }

    public static void main(String[] args) {
        String s1 = "hello";
        int n = 2;
        System.out.println(rotateString(s1, n));  // Output: "lohel"

        s1 = "abcde";
        String s2 = "cdeab";
        System.out.println(isRotatedString(s1, s2));  // Output: True
    }
}

在学习本题的过程中,我们不仅可以掌握字符串操作的技巧,还可以锻炼算法思维和解决问题的能力。通过对题目和实现方法的深入理解,我们可以进一步提升自己的编程水平。

最后,欢迎各位读者积极参与到力扣字符串专题的学习和讨论中来。