zoukankan      html  css  js  c++  java
  • 面试题:判断两个字符串是否互为回环变位(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));
    }
     
  • 相关阅读:
    Node_JS
    读JS高级——第五章-引用类型 _记录
    读JS高级(兼容&&BOM&&私有变量&&面向对象)
    JS高级设计第七章——复习知识点
    nodeJs抓取网页
    表单脚本api_contenteditable
    泛——复习js高级第三版
    nodeJS
    Eclipse布局问题小记
    再议负载均衡算法
  • 原文地址:https://www.cnblogs.com/kkkky/p/7832199.html
Copyright © 2011-2022 走看看