01.09. 字符串轮转

01.09. 字符串轮转

1、题目

字符串轮转。给定两个字符串s1s2,请编写代码检查s2是否为s1旋转而成(比如,waterbottleerbottlewat旋转后的字符串)。

1)示例1

输入:s1 = "waterbottle", s2 = "erbottlewat"
输出:True

2)示例2

输入:s1 = "aa", s2 = "aba"
输出:False

2、初步作答

2.1 思路

  • 旋转后的字符串与原字符串长度一定一致
  • 遍历比较字符串是否一致

2.2 做法

  • 比较字符串长度是否一致,不一致直接返回 false
  • 将字符串转换为字符数组
  • 遍历找到首字母相同的数组下标
  • 比较字符数组,不相同返回false,全部相同返回true

2.3 代码

public class String_rotation {
    public static void main(String[] args) {
        String s1 = "waterbottle";
        String s2 = "erbottlewat";
        boolean a = isFlipedString(s1,s2);
        System.out.println(a);
    }

    public static boolean isFlipedString(String s1, String s2) {
        if(s1.length() != s2.length()){
            return false;
        }
        if(s1.length() == 0){
            return true;
        }
        char[] S1 = s1.toCharArray();
        char[] S2 = s2.toCharArray();
        int num;
        for (int i = 0; i < S1.length; i++) {
            if(S1[0] == S2[i]){
                num = 0;
                for (int j = 0; j < S1.length; j++) {
                    if(S1[num++] == S2[(i+j)%S1.length]){
                        if(num == S1.length){
                            return true;
                        }
                    }else{
                        break;
                    }
                }
            }
        }
        return false;
    }
}

执行用时:1 ms, 在所有 Java 提交中击败了27.37%的用户
内存消耗:41.1 MB, 在所有 Java 提交中击败了23.99%的用户
通过测试用例:30 / 30

2.4 思考

暴力暴力加暴力,好像开始陷入了每次做题目先做出来的死循环,不会想着先想好能否优化,直接想着先做出来。有点难受!

3、其余解法

  • 力扣作者:jyd
class Solution {
    public boolean isFlipedString(String s1, String s2) {
        return s1.length() == s2.length() && (s2 + s2).contains(s1);
    }
}
  • 力扣作者:bobby996
class Solution {
    public boolean isFlipedString(String s1, String s2) {
            if(s1.length() != s2.length()) {
            return false;
        }
        String s = s2 + s2;
        return s.contains(s1);
    }
}
posted @   曦月宇望  阅读(72)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示