Arrays_Strings 利用isSubstring检查是否子串 @CareerCup

本文介绍了一种高效的算法,用于判断一个字符串是否为另一个字符串的旋转版本。通过将原字符串复制拼接,利用一次子串查找即可完成检测。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文:

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"的旋转字符串。


不多说了,和那道找链表是否有环一类的题目,属于你看过就会而且忘不掉,没看过就跪的神题。


package Arrays_Strings;

public class S1_8 {

	
	public static boolean isSubstring(String big, String small) {
		if(big.indexOf(small) >= 0) {
			return true;
		}
		return false;
	}
	
	// 检查办法就是把两个s1拼起来
	public static boolean isRotation(String s1, String s2) {
		int len = s1.length();
		if(len == s2.length() && len>0) {
			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];
			boolean is_rotation = isRotation(word1, word2);
			System.out.println(word1 + ", " + word2 + ": " + is_rotation);
		}
	}
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值