Showing posts with label Interview Questions. Show all posts
Showing posts with label Interview Questions. Show all posts

Sunday 25 November 2012

write a function to check given string matches with given pattern





public class isMatchingWithWildcard {
public static void main(String [] args){
String pattern = "*abc*def*.doc*";
String str = "adsfabcxyzdefgh.do1docx";
if(isMatching(str, pattern))
System.out.print("Matching");
else
System.out.print("Not Matching");
}
public static Boolean isMatching(String str, String pattern){
int l = pattern.length();
if(pattern.lastIndexOf("*") == l-1)
pattern= (String) pattern.subSequence(0, l-1);
if(pattern.charAt(0) == '*')
pattern= (String) pattern.subSequence(1, pattern.length());
pattern = pattern.replace("*", "__");
String [] patternArray = pattern.split("__");
String sorttenString =str;
for(String aPattern:patternArray){
String [] temp = sorttenString.split(aPattern);
if(temp.length==1 && (aPattern == patternArray[patternArray.length-1] 
&& !sorttenString.toLowerCase().contains(aPattern.toLowerCase())))
return false;
str.substring(temp[0].length()+aPattern.length());
}
return true;
}
}

Let me know your thoughts

Finding Pythagorean triplets in an array.



//   WORKING code in java with  time O(n^2)

import java.util.Arrays;
public class PythagoreanTripletsInArray {
public static double [] getSquare(String [] args){
double [] array = new double[args.length];
for(int i=0;i<args.length;i++){
double j=Integer.parseInt(args[i]);
array[i]=j*j;
}
return array;
}
public static void main(String [] args ){
double [] array =getSquare(args);
Arrays.sort(array);
Boolean flage = true;
for(double aInt : array){
for(int i=0,j=(array.length-1);i<j;){
double sum = array[i]+array[j]; 
if(aInt == sum){
System.out.println(Math.sqrt(aInt)+", "+Math.sqrt(array[i])+", "+Math.sqrt(array[j]));
flage = false;
break;
}
else if(aInt > sum)
i++;
else
j--;
}
}
if(flage)
System.out.print("No such solution exist");
}
}

Let me know your thoughts