Amazon Interview Question
Software Engineer / DevelopersTeam: Prime
Country: United States
Interview Type: Phone Interview
#include<stdio.h>
#include<string.h>
int occur(char[],char[]);
int occur(char sent[],char pattern[])
{
int count=0;
for(int i=0,j=i;sent[i]!='\0';)
{
if(sent[i+j]==pattern[j]&&pattern[j]!='\0')
{
j++;
}
else if(j==strlen(pattern))
{
count++;
i=i+j;
j=0;
}
else
{
i++;
j=0;
}
}
return count;
}
int main()
{
char sent[] = "aabaabaaabbbabababddfggaabbbasab";
char pattern[] = "aba";
int result = occur(sent,pattern);
printf("\nNo of Occurrences --- > %d",result);
return 0;
}
public class FindPatternOccurrences {
public static void main(String[] args) {
String str = "aabababcfdc";
String pattern = "ab";
matchPattern(str, pattern);
}
public static void matchPattern(String str, String pattern) {
int count = 0;
for (int i = 0; i < str.length() - 1; i++) {
String str1 = str.substring(i, i + 2);
if (str1.equals(pattern))
count++;
}
System.out.println("NUmber of occurrences= " + count);
}
}
This prints the number of occurrences of the pattern:
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class SubString {
public static void main(String[] args) {
String str= "abbbacctlkababcdjlkcccabcdaaabbbabcd";
String temp = "abcd";
Map<String,Integer> map = new HashMap<>();
int len = str.length();
System.out.println(len);
int templen = temp.length();
for(int i=0;i<len-templen+1;i++){
if(map.containsKey(str.substring(i,i+templen)))
map.put(str.substring(i,i+templen), map.get(str.substring(i,i+templen))+1);
else
map.put(str.substring(i,i+templen), 1);
}
System.out.println(map.get(temp));
}
}
you are inserting every substring into the hasmap and only getting the desired string count in the end, wasting a lot of memory, since you're only interested on the target string why don't you do just count it's occurrences like this:
public static void main(String[] args) {
String str= "abbbacctlkababcdjlkcccabcdaaabbbabcd";
String temp = "abcd";
int len = str.length();
int count = 0;
int templen = temp.length();
for(int i=0;i<len-templen+1;i++){
String tempStr = str.substring(i,i+templen));
if (tempStr.equals(temp)) {
count ++;
}
}
System.out.println(count);
}
simple kmp
- ssikka25 February 05, 2014