更新:我有两个字符串。
String a = "is am are has have was " //Helping verbs
String b= " Robert and william are English Robert has a car he was living in England " //Sentence
更新:从字符串a中选择第一个子字符串,然后在字符串b的子字符串中搜索该子字符串。如果找到,则返回两者的索引号。然后继续在第二个String中找到第一个String的第二个subString,依此类推,直到last。
String stringA = "one two three four five six " ;
String stringB = " eleven two four twelve thirteen ";
String[] stringOne = stringA.split(" ");
String[] stringTwo = stringB.trim().split(" ");
Map<Integer,Integer> mapMatchingStrings = new HashMap<>();
IntStream.range(0,stringOne.length).forEach(indexOfStringOne -> IntStream.range(0,stringTwo.length).forEach(indexOfStringTwo ->
{
if(Objects.equals(stringOne[indexOfStringOne],stringTwo[indexOfStringTwo])){
mapMatchingStrings.put(indexOfStringOne,indexOfStringTwo);
}
}
));
System.out.println(mapMatchingStrings);
输出:-{1 = 1,3 = 2}
String a = "one two three four five six";
String b = "eleven two four twelve thirteen";
StringTokenizer aT = new StringTokenizer(a," "/*delimiter(space or comma)*/);
while (aT.hasMoreTokens()) {
String indexA = aT.nextToken();
StringTokenizer bT = new StringTokenizer(b," ");
int index = 0;
while(bT.hasMoreTokens()) {
if(bT.nextToken().equals(indexA))System.out.println("Found Match:"+index);
index++;
}
}
String a = "one two three four five six ";
String b= " eleven two four twelve thirteen " ;
List<String> aSub = Arrays.asList(a.split(" "));
List<String> bSub = Arrays.asList(b.split(" "));
for(String s1 :aSub){
for(String s2 :bSub){
if(s1.equalsIgnoreCase(s2)){
System.out.println( s1+" exists and is found in index "+ bSub.indexOf(s1));
}
}
}
结果:存在两个并且在索引2中找到
存在四个并且在索引3中找到
//Big O of N*N solution
class SubString{
public static void main(String [] args)
{
System.out.println(new SubString().getCommonSubString("abcdefg","zycdemm"));
}
public int getCommonSubString(String A, String B)
{
int ans =0;
for(int i=0;i<A.length();i++)
{
int c=0;
int k =i;
for(int j=0;k<A.length()&&j<B.length();j++)
{
if(A.charAt(k)==B.charAt(j))
{
c++;
ans = Math.max(ans, c);
k++;
}else
{
c=0;
k=i;
}
}
}
return ans;
}
}