0021力扣796题---旋转字符串

力扣796题---旋转字符串

给定两个字符串,s和goal。如果在若干次旋转操作之后,s能变成goal,那么返回true。

s的旋转操作 就是将s最左边的字符移动到最右边。

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

示例1:

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

示例2:

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

提示:

1 <= s.length, goal.length <= 100

s和goal由小写英文字母组成

方法一:搜索子字符串
如果s与goal的长度不一样,那么无论怎么旋转,s 都不能得到goal,返false。
字符串s+s 包含了所有s可以通过旋转操作得到的字符串,只需要检查goal是否为s+s的子字符串即可。

方法代码:

    public boolean rotateString(String s, String goal) {
        return s.length() == goal.length() && (s + s).contains(goal);
    }

测试:

public class Main {
    public static void main(String[] args) {
        String str = "abcdefg";
        String goal = "cdefcab";
        Main solution = new Main();
        System.out.println(solution.rotateString(str, goal));
    }

    public boolean rotateString(String s, String goal) {
        return s.length() == goal.length() && (s + s).contains(goal);
    }
}


输出:true


方法二:模拟


首先,如果s和goal的长度不一样,那么无论怎么旋转,s都不能得到goal,返回false。
在长度一样(都为n)的前提下,假设s旋转i位,则与goal中的某一位字符goal[j]对应的原s中的字符应该为s[(i+j)mod n]。在固定i的情况下,遍历所有 j,若对应字符都相同,则返回true。否则,继续遍历其他候选的i。若所有的i都不能使s变成goal,则返回false。

方法代码:

    public boolean rotateString(String s, String goal) {
        int m = s.length(), n = goal.length();
        if (m != n) {
            return false;
        }
        for (int i = 0; i < n; i++) {
            boolean flag = true;
            for (int j = 0; j < n; j++) {
                if (s.charAt((i + j) % n) != goal.charAt(j)) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                return true;
            }
        }
        return false;
    }

测试:

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        //BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str = "abcdefg";
        String goal = "cdefgab";
        Main solution = new Main();
        System.out.println(solution.rotateString(str, goal));
    }

    public boolean rotateString(String s, String goal) {
        int m = s.length(), n = goal.length();
        if (m != n) {
            return false;
        }
        for (int i = 0; i < n; i++) {
            boolean flag = true;
            for (int j = 0; j < n; j++) {
                if (s.charAt((i + j) % n) != goal.charAt(j)) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                return true;
            }
        }
        return false;
    }
}


输出:true
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值