• Cracking the coding interview--Q1.8


    题目

    原文:

    Assume you have a method isSubstring which checks if one word is a substring of another. Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call to isSubstring ( i.e., “waterbottle” is a rotation of “erbottlewat”).

    译文:

    假设你有一个isSubstring函数,可以检测一个字符串是否是另一个字符串的子串。 给出字符串s1和s2,只使用一次isSubstring就能判断s2是否是s1的旋转字符串, 请写出代码。旋转字符串:"waterbottle"是"erbottlewat"的旋转字符串。

    解答

    题目说我们使用一次isSubstring函数就可以判断s2是否是s1的旋转字符串, 如果从原始字符串s1和s2直接入手肯定不行,因为它们根本不存在子串关系。 如果不断地旋转字符,然后调用isSubstring,又需要调用多次的isSubstring。 而且通过旋转字符再判断,可以直接用等号判断,根本用不上isSubstring。

    既然如此,我们就要考虑去改变原始字符串。要判断a串是否是b串的子串, 一般情况下都会有b串长度大于a串,长度相等的话就直接判断它们是不是相等的串了。 我们可以考虑把串s1变长,然后调用一次isSubstring判断s2是否是s1变长后的子串, 如果是,就得出s2是s1的旋转字符串。s1怎么变长呢?无非就是s1+s1或是s1+s2, s2一定是s1+s2的子串,因此这样做没有任何意义。而s1+s1呢? 我们就上面的例子进行讨论:s1=waterbottle,s2=erbottlewat. 则:

    s1 + s1 = waterbottlewaterbottle

    很容易可以发现,s1+s1其实是把s1中每个字符都旋转了一遍,而同时保持原字符不动。 比如waterbottle向右旋转2个字条应该是:terbottlewa,但如果同时保持原字符不动, 我们得到的就是waterbottlewa,而terbottlewa一定是waterbottlewa的子串, 因为waterbottlewa只是在terbottlewa的基础上再加上一条原字符不动的限制。 因此s1+s1将包含s1的所有旋转字符串,如果s2是s1+s1的子串,自然也就是s1 的旋转字符串了。

    代码如下:

    package cha1;
    
    public class A008 {
        
        public static boolean isRotate(String s1, String s2) {
            if (s1.length() != s2.length())
                return false;
            s1 = s1 + s1;
            if (s1.contains(s2))
                return true;
            return false;
        }
        
        public static void main(String[] args) {
            System.out.println(isRotate("loull", "lloul"));
            System.out.println(isRotate("loull", "lluol"));
        }
    }
  • 相关阅读:
    linux 使用crontab定时任务+shell脚本删除tomcat日志elasticsearch日志索引
    【转】Java8 Stream 流详解
    Mongo查询list数组中一个字段大于特定条数
    安装Elasticsearch出现 node validation exception 的问题处理
    mockito使用教程
    rocketmq4.4配置日志路径等级
    使用ResponseBodyAdvice统一包装响应返回String的时候出现java.lang.ClassCastException: com.xxx.dto.common.ResponseResult cannot be cast to java.lang.String
    服务器22端口连接超时 ssh: connect to host *** port 22: Operation timed out
    【JAVA基础】24 递归练习
    【JAVA基础】23 IO流-其他流
  • 原文地址:https://www.cnblogs.com/549294286/p/3191545.html
Copyright © 2020-2023  润新知