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));
    }
     
  • 相关阅读:
    npm --save-dev 与 --save 的区别
    Vue 简单实例 购物车2
    Vue 简单实例 购物车1
    node.js富文本编辑器
    使用jquery操作session
    浏览器窗口之间传递数据
    批量修改文件编码格式
    具有动态效果的响应式设计
    Ajax请求全局配置
    html实体转换
  • 原文地址:https://www.cnblogs.com/kkkky/p/7832199.html
Copyright © 2011-2022 走看看