Advertisement

【字符串】判断s2是否是s1的旋转字符串2

阅读量:

题目
Suppose you have a method called isSubstring that verifies whether one string is contained within another. Given two strings, S1 and S2, develop code to determine if S2 constitutes a rotational variant of S1 by employing just one invocation of the isSubstring function. For instance, 'waterbottle' qualifies as a rotation of 'erbottlewat'.

假设你有一个名为isSubstring的函数,它可以检测一个字符串是否为另一个字符串的子串。给定两个字符串s1和s2,请编写代码以仅需调用一次该函数即可判断s2是否为s1的一个旋转子串。例如,在示例中可以观察到'waterbottle'与'erbottlewat'之间存在这样的旋转关系。

思路:

只需关注一个关键点:通过拼接得到的字符串中包含了所有可能的s1的旋转版本;也就是说,问题转化为检查s2是否为该拼接字符串中的子串。

复制代码
    //判断s2是不是s1的子串
    bool isSubstring(string s1, string s2){
    if(s1.find(s2) != string::npos) return true;
    else return false;
    }
     
    //防范一下,以及调用:isSubstring(s1+s1, s2)
    bool isRotation(string s1, string s2){
    if(s1.length() != s2.length() || s1.length()<=0)
        return false;
    return isSubstring(s1+s1, s2);
    }
    
    
      
      
      
      
      
      
      
      
      
      
      
      
    
    代码解读

比如:

s1 = waterbottle,某个旋转字符串是 erbottlewat

s1 + s1 = waterbottlewaterbottle

全部评论 (0)

还没有任何评论哟~