java - 返回出现在第二个单词中的第一个单词的字谜。

标签 java algorithm

给定两个词,确定第一个词或它的任何变位词是否出现在第二个词的连续字符中。例如,teaslate 的最后三个字母中显示为变位词,但 letslate 中未显示为变位词 即使 let 的所有字母都出现在石板上。 返回出现在第二个单词中的第一个单词的字谜。

Sample Input 1
tea
slate

Sample Output1
ate
Sample Input 2
let
slate

Sample Output2
NONE

我在下面试过被击中

public static boolean testAnagram(String originalWord, String containedWord)
{
char [] first = originalWord.toCharArray();//Get the first word and store it into a character array.
char [] second = containedWord.toCharArray();//Get the second word and store it into a character array.
int [] index = new int[second.length];//An int array that stores the index of matching letters contained in the original array.
int counter = 0;//Keep count of the index storage position.

//Compare each character of both words.

for(int i = 0; i < second.length; i++)
{
  for(int j = 0; j < first.length; j++)
  {
    if(second[i] == first[j])
    {
      index[counter] = j; //Store matching letters.
      counter++; //Increment the index storage position.
      break;//Break for loop.
    }
  }
}

if(counter < second.length)return false;//If not all letters were found.

//get the distance between the indices which should be no more than one
//less than the contained word length (to qualify as an anagram)

for(int i = 0; i < index.length; i++)
{
  for(int j = 0; j = second.length) 
  {
    //stuck here
    return ;
  }
}

//If all qualifications are met.
return ;
}

最佳答案

我建议您执行以下操作:

  1. 遍历第二个单词中的每个字符(例如 slate)
  2. 当您找到第一个单词中包含的字符时,获取以该字符开头且长度为第一个单词的子字符串。
  3. 检查这个子串是否是第一个单词的变位词。

     String getSubAnagram (String s1, String s2){
            for (int i = 0; i = s1.length(); i++) {
                if(s1.indexOf(s2.charAt(i)) >-1){
                    if(isAnagram(s1, s2.substring(i, s1.length()+i)))
                        return s2.substring(i, s1.length()+i);
                }
            }
            return null;
     }

关于java - 返回出现在第二个单词中的第一个单词的字谜。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22947537/

相关文章:

java - 返回最低和最高键之间的差异 - 二叉搜索树

algorithm - 来自有序和级别顺序遍历的二叉树?

java - Xtend lambda 表达式重载 Xtext QuickFix API

java - 找到部署在tomcat中的web应用的pom.xml

algorithm - linux diff -y 的算法是什么?

Java 算法 : pair list entries by multiple case criteria

algorithm - 如何理解给定示例中的大 O 符号

c# - 欧拉计划问题 3 帮助

java - 用java实现我自己的序列化

java - 将 Collection 和 Iterator 接口(interface)实现为内部类