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));
        }
    }
  • 相关阅读:
    [转]WPF 4 媒体播放器(MediaElement)
    WPF简单的文件资源管理
    shell脚本自动化部署
    Linux知识
    单例模式及其四种实现方式
    支付宝对接步骤 (app)
    《异类》读书摘要(上)
    Linux初级指令
    项目构建基础统一结果,统一异常,统一日志
    git看这一篇就够用了
  • 原文地址:https://www.cnblogs.com/giraffe/p/3186770.html
Copyright © 2011-2022 走看看