面试题:判断两个字符串是否互为回环变位(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));
}

 

 

 
posted @ 2017-11-14 13:56  Kkky  阅读(1061)  评论(0编辑  收藏  举报