首页 > 其他分享 >leetcode-796-easy

leetcode-796-easy

时间:2022-11-26 20:33:58浏览次数:63  
标签:796 false goal int ++ easy return leetcode String

Rotate String

Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s.

A shift on s consists of moving the leftmost character of s to the rightmost position.

For example, if s = "abcde", then it will be "bcdea" after one shift.
Example 1:

Input: s = "abcde", goal = "cdeab"
Output: true
Example 2:

Input: s = "abcde", goal = "abced"
Output: false
Constraints:

1 <= s.length, goal.length <= 100
s and goal consist of lowercase English letters.

思路一:把字符串 s 分成前后两部分,前后部分分别和 goal 对比

public boolean rotateString(String s, String goal) {
    if (s.length() != goal.length()) return false;

    for (int i = 0; i < s.length(); i++) {
        if (match(s, goal, i)) {
            return true;
        }
    }

    return false;
}

public boolean match(String s, String goal, int idx) {
    int y = 0;
    for (int i = idx; i < s.length(); i++, y++) {
        if (goal.charAt(y) != s.charAt(i)) return false;
    }

    for (int i = 0; i < idx; i++, y++) {
        if (goal.charAt(y) != s.charAt(i)) return false;
    }

    return true;
}

标签:796,false,goal,int,++,easy,return,leetcode,String
From: https://www.cnblogs.com/iyiluo/p/16928250.html

相关文章