给定两个词,确定第一个词或它的任何变位词是否出现在第二个词的连续字符中。例如,tea
在 slate
的最后三个字母中显示为变位词,但 let
在 slate 中未显示为变位词
即使 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 ;
}
最佳答案
我建议您执行以下操作:
- 遍历第二个单词中的每个字符(例如 slate)
- 当您找到第一个单词中包含的字符时,获取以该字符开头且长度为第一个单词的子字符串。
检查这个子串是否是第一个单词的变位词。
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/