java - 面试题: Check if one string is a rotation of other string

标签 java c++ c

我的一个 friend 今天在面试软件开发人员的职位时被问到以下问题:

给定两个字符串 s1s2您将如何检查 s1s2旋转版本?

示例:

如果 s1 = "stackoverflow"那么以下是它的一些旋转版本:

"tackoverflows"
"ackoverflowst"
"overflowstack"

其中 "stackoverflwo" 不是旋转版本。

他给出的答案是:

Take s2 and find the longest prefix that is a sub string of s1, that will give you the point of rotation. Once you find that point, break s2 at that point to get s2a and s2b, then just check if concatenate(s2a,s2b) == s1

对我和我的 friend 来说,这似乎是一个很好的解决方案。但面试官不这么认为。他要求一个更简单的解决方案。请在 Java/C/C++ 中告诉我你将如何做到这一点来帮助我。 ?

提前致谢。

最佳答案

首先确保 s1s2 的长度相同。然后检查 s2 是否是 s1s1 连接的子字符串:

algorithm checkRotation(string s1, string s2) 
  if( len(s1) != len(s2))
    return false
  if( substring(s2,concat(s1,s1))
    return true
  return false
end

在 Java 中:

boolean isRotation(String s1,String s2) {
    return (s1.length() == s2.length()) && ((s1+s1).indexOf(s2) != -1);
}

关于java - 面试题: Check if one string is a rotation of other string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2553522/

相关文章:

java - 仅使用 XSD 的 JAX WS WebService 实现

java - Ebean:奇怪的结果

c++ - Cygwin+ eclipse : How does one hide a console window in n OpengGL based program by without getting unrecognized emulation mode error?

c++ - GCC 中的嵌套结构位域对齐

c - 对一段简单代码的按位运算

c++ - 带有尾随注释的多行预处理器宏

java - 在 java 中使用 HTML 和现有变量

java - 当我阅读此文件时,有人可以帮我在代码中添加行计数器吗

c++ - QSplitter:如何使第二列更小?

c - 在将指针作为参数的函数内操作指针值