面试题:判断两个字符串是否互为回环变位(Circular Rotaion)

题干:
 
如果字符串 s 中的字符循环移动任意位置之后能够得到另一个字符串 t,那么 s 就被称为 t 的回环变位(circular rotation)。
 
例如,ACTGACG 就是 TGACGAC 的一个回环变位,反之亦然。判定这个条件在基因组序列的研究中是很重要的。
编写一个程序检查两个给定的字符串 s 和 t 是否互为回环变位。
 
A string s is a circular rotation of a string t if it matches when the characters are circularly shifted by any number of positions;
e.g., ACTGACG is a circular shift of TGACGAC, and vice versa. Detecting this condition is important in the study of genomic sequences.
Write a program that checks whether two given strings s and t are circular.

 
解法一:
将s拆分成左右两部分,然后另令s'=右+左,遍历所有情况。如果是回环字符串的话,其中会有 s'=t 的情况。
 1 public static boolean isCircularRotation(String s, String t) {
 2         if (s.length() != t.length())
 3             return false;
 4         int sLen = s.length();
 5         for (int i = 0; i <= sLen; i++) {
 6             // 注意subString的后角标的界限
 7             String sLeft = s.substring(0, i);
 8             String sRigth = s.substring(i + 1, sLen);
 9             if ((sRigth + sLeft).equals(t))
10                 return true;
11         }
12         return false;
13     }

解法二:(巧妙)

public static boolean isCircularRotation_1(String s, String t) {
    return (s.length() == t.length() && (t + t).contains(s));
}

 

 

 

转载于:https://www.cnblogs.com/kkkky/p/7832199.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值