LeetCode面试题 01.09 字符串轮转

题目

解答

java 复制代码
package leetcode.editor.cn;

//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public boolean isFlipedString(String s1, String s2) {
        if (s1 == null && s2 == null) {
            return true;
        }

        if (s1 == null || s2 == null) {
            return false;
        }

        if (s1.isEmpty() && s2.isEmpty()) {
            return true;
        }

        if (s1.length() != s2.length()) {
            return false;
        }

        for (int i = 0, length = s1.length(); i < length; ++i) {
            String ss1 = s1.substring(i);
            if (s2.startsWith(ss1)) {
                if (s2.equals(s1.substring(i, s1.length()) + s1.substring(0, i))) {
                    return true;
                }
            }
        }

        return false;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

测试用例

java 复制代码
package leetcode.editor.cn;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class SolutionTest {
    private Solution s = null;

    @Before
    public void setUp() throws Exception {
        s = new Solution();
    }

    @Test
    public void test1() {
        Assert.assertTrue(s.isFlipedString("waterbottle", "erbottlewat"));
        Assert.assertTrue(s.isFlipedString("erbottlewat", "waterbottle"));
    }

    @Test
    public void test2() {
        Assert.assertFalse(s.isFlipedString("aa", "aba"));
        Assert.assertFalse(s.isFlipedString("aba", "aa"));
    }

    @Test
    public void test3() {
        Assert.assertTrue(s.isFlipedString("waterbottle", "waterbottle"));
    }

    @Test
    public void test4() {
        Assert.assertFalse(s.isFlipedString("abcd", "acdb"));
    }
}

理解并掌握StringstartsWithsubstring的使用方法。

相关推荐
怒放吧德德5 小时前
Netty 4.2 入门指南:从概念到第一个程序
java·后端·netty
雨中飘荡的记忆6 小时前
大流量下库存扣减的数据库瓶颈:Redis分片缓存解决方案
java·redis·后端
心之语歌9 小时前
基于注解+拦截器的API动态路由实现方案
java·后端
华仔啊10 小时前
Stream 代码越写越难看?JDFrame 让 Java 逻辑回归优雅
java·后端
ray_liang10 小时前
用六边形架构与整洁架构对比是伪命题?
java·架构
Ray Liang12 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
Java水解12 小时前
Java 中间件:Dubbo 服务降级(Mock 机制)
java·后端
SimonKing16 小时前
OpenCode AI辅助编程,不一样的编程思路,不写一行代码
java·后端·程序员
FastBean16 小时前
Jackson View Extension Spring Boot Starter
java·后端
Seven9717 小时前
剑指offer-79、最⻓不含重复字符的⼦字符串
java