Реализация алгоритма полный перебор
Помогите пожалуйста сделать алгоритм Brute Force. Который покажет все места в массиве где есть такие же знаки. Например
Ищу: ССQ
Массив знаков: QCCQCQCCCQCCQ
Результат :1,7,10.
public class zad1 {
public static char[] toTab(String str) {
char[] tab = new char[str.length()];
for(int i=0; i<str.length(); i++) {
tab[i] = str.charAt(i);
}
return tab;
}
public static int find(char t[], char w[]) {
int i=0,j=0;
int M=w.length, N=t.length;
while( (j<M) && (i<N) ){
if(t[i]!=w[j]){ // *
i-=j-1;
j=-1;
}
i++; // **
j++;
}
if(j==M)
return i-M;
else
return -1; // нечего нету.
}
public static String findTo(char t[], char w[]) {
String str = "";
while(find(t, w) > 0) {
int counter = find(t, w);
str = str+find(t, w)+", ";
for(int i=0; i<w.length; i++) {
t[counter+i] = ' ';
}
for(int i=0; i<t.length; i++) {
System.out.print(t[i]+", ");
}
counter = 0;
}
return str;
}
public static void main(String[] args) {
String text = "QCCQCQCCCQCCQ";
String pattern = "CCQ";
char[] textTab = toTab(text);
char[] patternTab = toTab(pattern);
for(int i=0; i<textTab.length; i++) {
System.out.print(textTab[i]+", ");
}
System.out.println();
for(int i=0; i<patternTab.length; i++) {
System.out.print(patternTab[i]+", ");
}
System.out.println();
System.out.print(findTo(textTab, patternTab));
}
}
Ответы (1 шт):
Автор решения: Дмитрий
→ Ссылка
Как-то все слишком сложно у вас... На быструю руку это выглядит так и решается фактически в одну строчку кода:
public class Zad1 {
public static void main(String[] args) {
String text = "QCCQCQCCCQCCQ";
String pattern = "CCQ";
int position = -1;
while((position = text.indexOf(pattern, position+1))!=-1) System.out.println(position);;
}
}
или так
public class Zad1 {
public static void main(String[] args) {
String text = "QCCQCQCCCQCCQ";
String pattern = "CCQ";
int position = -1;
while((position = find(text, pattern, position+1))!=-1) System.out.println(position);
}
public static int find(String text, String pattern, int start) {
for (int i = start; i < text.length(); i++) {
if (pattern.charAt(0)==text.charAt(i)
&& text.length()>=(i+pattern.length())
&& text.substring(i, i+pattern.length()).equals(pattern)) return i;
}
return -1;
}
}