Flipkart Interview Question
SDE-2sCountry: United States
import java.util.Scanner;
import java.util.regex.Pattern;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter pattern: ");
String pattern = sc.next();
System.out.println("Enter string: ");
String input = sc.next();
if(Pattern.matches(pattern, input)){
System.out.println("There is a match");
} else {
System.out.println("There isn't a match");
}
}
}
/* Adopted from Rob Pike's implementation */
#include <iostream>
#include <stdio.h>
using namespace std;
bool RegExMatchHelper(char* regex, char* text);
bool RegExMatchKleeneStar (char c, char* regex, char* text){
do {
if(RegExMatchHelper(regex, text)) return true;
} while (*text != '\0' && (*text++ == c || c == '.'));
return false;
}
bool RegExMatchHelper(char* regex, char* text){
if(regex[0] == '\0') return true;
if(regex[0] == '$' && regex[1] == '\0') return *text == '\0';
if(regex[1] == '*') {
return RegExMatchKleeneStar(regex[0], regex+2, text);
}
if(*text != '\0' && (*text++ == regex[0] || regex[0] == '.')) {
return RegExMatchHelper(regex+1, text);
}
return false;
}
bool RegExMatcher (char* regex, char* text){
if(regex[0] == '\0') return true;
if(regex[0] == '^') {
return RegExMatchHelper(regex+1, text);
} else {
do {
if(RegExMatchHelper(regex, text)) return true;
} while (*text++ != '\0');
}
return false;
}
int main(int argc, char** argv) {
if(argc != 3) cout << "Wrong format\n";
if(RegExMatcher(argv[1],argv[2])) cout << "Match\n";
else cout << "Doesn't match\n";
return 0;
}
- Anonymous January 12, 2016