我有两个字符串
s1 = "cAda"
s2 = "AbrAcadAbRa"
需要在第二个字符串中查找字符串1的序列。
output = 2 which is (Acad, cadA)
答案 0 :(得分:1)
输入:
4
11
cAda
AbrAcadAbRa
输出:2
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
class GFG {
public static void main (String[] args) {
//code
Scanner in = new Scanner(System.in);
int output = 0;
int ip1 = Integer.parseInt(in.nextLine().trim());
int ip2 = Integer.parseInt(in.nextLine().trim());
String ip3 = in.nextLine().trim();
String ip4 = in.nextLine().trim();
output = appearanceCount(ip1,ip2,ip3,ip4);
System.out.println(String.valueOf(output));
}
public static int appearanceCount(int input1,int input2,String
input3,String input4)
{
//Write code here
int a= permute(input3,0,input3.length()-1,input4);
return a;
}
static int count=0;
public static int permute(String str, int l, int r,String mainstr)
{
if (l == r){
if(mainstr.contains(str)){
count++;
}
}
else
{
for (int i = l; i <= r; i++)
{
str = swap(str,l,i);
permute(str, l+1, r,mainstr);
str = swap(str,l,i);
}
}
return count;
}
public static String swap(String a, int i, int j)
{
char temp;
char[] charArray = a.toCharArray();
temp = charArray[i] ;
charArray[i] = charArray[j];
charArray[j] = temp;
return String.valueOf(charArray);
}
}
答案 1 :(得分:0)
你走了:
public static boolean containsWord(String str, String word){
for(char c : word.toCharArray()){
if(!str.toLowerCase().contains(String.valueOf(c).toLowerCase())){
return false;
}
}
return true;
}
使用两个字符串调用上述方法,例如:
String s1 = "cAda";
s1 = s1.chars().mapToObj(c -> String.valueOf((char) c)).distinct().collect(Collectors.joining()); //Remove duplicate characters
String s2 = "AbrAcadAbRa";
int length = s1.length();
for(int i=0 ; i< s2.length() - s1.length() ; i++){
if(containsWord(s2.substring(i, i+length), s1)){
System.out.println(s2.substring(i, i+length));
}
}
如果您想要区分大小写,那么您可以在.toLowerCase()
方法中删除containsWord
。
答案 2 :(得分:0)
也可能是这样
int findSequence(final String pat, final String str) {
String modPat = pat + pat;
int count = 0;
for (int i = 0; i < pat.length(); i++) {
String substring = modPat.substring(i, i + pat.length());
int indexOf = str.toLowerCase().indexOf(substring.toLowerCase());
if (indexOf != -1) {
System.out.println(str.substring(indexOf, indexOf + pat.length()));
count++;
}
}
return count;
}