Two ways to solve the problem of rotating strings

Fourth, rotate the string

4.1. Requirements for the title

​ Given two strings, s and goal. Returns true if s can become goal after several rotation operations. The rotation operation of s is to move the leftmost character of s to the rightmost.

例如, 若 s = 'abcde',在旋转一次之后结果就是'bcdea' 。

示例 1:

输入: s = "abcde", goal = "cdeab"
输出: true

示例 2:

输入: s = "abcde", goal = "abced"
输出: false

提示:

1 <= s.length, goal.length <= 100
s 和 goal 由小写英文字母组成

Source: LeetCode
Link: https://leetcode-cn.com/problems/rotate-string

4.2, problem-solving ideas

the first method:

​ First determine whether the lengths of the two strings are equal, and then use the contains() function to compare the two strings.
  The contains() method returns true if and only if this string contains the specified sequence of char values.

The second method:

​ First determine whether the lengths of the two strings are equal, and compare the various substrings of the string s with the goal through a loop, using the charAt(int index) method.
The charAt(int index) method is a method that can be used to retrieve the String instance of the character at a specific index, and the charAt() method returns the char value at the specified index position.
​​ The charAt(int index) method returns the character at index, and the value range of index is [0 , s.length-1].

4.3. Algorithms

the first method:

class Solution {
    
    
    public boolean rotateString(String s, String goal) {
    
    
        //第一种方法
        //先判断两个字符串的长度是否相等,再使用contains()函数将两个字符串进行比较
        //contains()方法返回true,当且仅当此字符串包含指定的char值序列
        //如果此字符串包含,此方法返回true,否则返回false。
        return s.length() == goal.length() && (s + s).contains(goal);
}

The second method:

class Solution {
    
    
    public boolean rotateString(String s, String goal) {
    
    
        //第二种方法
        int n = s.length();
        int m = goal.length();
        //先判断两个字符串的长度是否相等,如果不相等,那就没有比较的必要了
        if(n != m){
    
    
            return false;
        }
        //通过循环将字符串s的各种子字符串与goal进行比较
        for(int i = 0;i < m;i++){
    
    
            boolean a = true;
            for(int j = 0;j < m;j++){
    
    
                if(s.charAt((i+j)%m) != goal.charAt(j)){
    
    
                    a = false;
                    break;
                }
            }
            if(a){
    
    
                return true;
            }
        }
        return false;
    }
}

Guess you like

Origin blog.csdn.net/qq_52916408/article/details/124051191