Srikanth Raj
BAN USERI have used Hashing to find the solution
static void printWords(char[] arr, String[] dict) {
HashSet<Character> hs = new HashSet<Character>();
int i;
for(i =0;i<arr.length;i++)
hs.add(arr[i]);
for(String s: dict){
for(i =0;i<s.length();i++) {
if(hs.contains(s.charAt(i)))
continue;
else
break;
}
if(i == s.length()) // match found
System.out.println(s);
}
}
int a[] = {1,4,5,7,11,14,20};
Arrays.sort(a);
int target = 14;
int i =0;
int j = a.length -1;
int count =0;
while(a[i] < target) {
while (a[i] + a[j] >= target) {
j --;
}
count += Math.max(j - i + 1, 1);
i ++;
}
System.out.println(count);
Here is my In place algorithm without using any extra variable:
for(int i =0;i<m;i++) {
for(int j=0;j<n;j++) {
if(a[i][j] == 0){
a[i][0] = 0;
a[0][j] = 0;
}
}
}
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(a[i][0] == 0 || a[0][j] == 0)
a[i][j] =0;
}}
for(int i =0;i<m;i++) {
for(int j=0;j<n;j++) {
System.out.print(a[i][j]);
}
System.out.println();
}}
This looks to me like a KMP Algorithm but taking integers into consideration. Pattern is the SubArray and We have to find that pattern with index in the main Array. Code below:
- Srikanth Raj April 25, 2017int [] pat = {5,7};
int [] text = {1,2,3,5,8,7,6,9,5,7,3,0,5};
int a [] = new int[pat.length];
int j =0;
a[j] = 0;
for(int i =1;i< pat.length;i++) {
if(pat[i] == pat[j]) {
a[i] = j+1;
j++;
}
else {
if(j >0) {
j = a[j-1];
while(pat[j] != pat[i] && j >0)
{
j = a[j-1];
}
if(pat[j] == pat[i]) {
a[i] = j +1;
j++;
}
}
if(j==0)
a[i] = j;
}
}
//for(int i =0;i<a.length;i++)
//System.out.print(a[i] +"\t");
StringBuilder sb = new StringBuilder();
int count = 0;
int []index = new int[10];
j =0;
for(int i =0; i < text.length;i++){
if(pat[j] == text[i]){
//count++;
j++;
if(j == pat.length){
index[count] = i - pat.length+1;
System.out.println("Index:" + (i-pat.length+1));
count++;
j=0;
}
}
else {
if(j>0 && i >0) {
j = a[j-1];
i--;
}
else
{
j=0;
}}}