zoukankan      html  css  js  c++  java
  • 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"的旋转字符串。

    解答:

    如果s1是s2的旋转字符串,那么我们一定能找到一个切割点将s1分割成xy,并且yx等于s2。例如:

    s1 = xy = waterbottle
    x = wat
    y = erbottle
    s2 = yx = erbottlewat

    那么我们可以知道yx一定是xyxy的一个子串,也就是说,s2一定是s1s1的子串。所以这个题目的解法也就一目了然了。

    public class Main {
    
        public static boolean isSubstring(String s1, String s2) {
            if(s1 == null || s2 == null)
                return false;
            if(s1.contains(s2))
                return true;
            else
                return false;
        }
        
        public static boolean isRotation(String s1, String s2) {
            return isSubstring(s1+s1,s2);
        }
    
        public static void main(String args[]) {
            String s1 = "waterbottle";
            String s2 = "erbottlewat";
            System.out.println(isRotation(s1,s2));
        }
    }
  • 相关阅读:
    c++重载operator的示例 非原创
    L1-2 倒数第N个字符串 (15 分)真坑
    error C2955: “std::xx”: 使用 类 模板 需要 模板 参数列表
    时间超限问题处理(c++)
    C语言实验1
    心理魔术
    闰年作业
    20180425
    Labview学习笔记-条件结构的两个问题
    判断文件目录或者文件是否存在
  • 原文地址:https://www.cnblogs.com/giraffe/p/3186770.html
Copyright © 2011-2022 走看看