1.8

来源:互联网 发布:大学宿舍网络怎么样 编辑:程序博客网 时间:2024/04/29 05:46

Topic: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 is Substring (e.g.“waterbottle” is a rotation of “erbottlewat”)

// 知识点:String.indexOf()返回String对象内第一次出现子字符串的字符位置,如果未找到,返回-1.

 

// 关键点:判断时,两字符串长度必须相等,且不为空

// 方法1: just check whether s2 is substring of s1+s1

public class CC1_1 {public static boolean isSubstring(String s, String t) {if (s.indexOf(t) >= 0) {return true;} else {return false;}}public static boolean isRotation(String s1, String s2) {    /* check that s1 and s2 are equal length and not empty */    if (s1.length() == s2.length() && s1.length() > 0) {     /* concatenate s1 and s1 within new buffer */    String s1s1 = s1 + s1;    return isSubstring(s1s1, s2);    }    return false;}public static void main(String[] args) {String[][] pairs = {{"apple", "pleap"}, {"waterbottle", "erbottlewat"}, {"camera", "macera"}};for (String[] pair : pairs) {String word1 = pair[0];String word2 = pair[1];System.out.println(word1 + ", " + word2 + ": " + isRotation(word1, word2));}}}
//结果apple, pleap: truewaterbottle, erbottlewat: truecamera, macera: false



 

 

原创粉丝点击