fork(5) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static boolean matches(String pattern, String str) {
  11. // base case 1: we came to end in both string and pattern -> matched
  12. if (str.length() == 0 && pattern.length() == 0) {
  13. return true;
  14. }
  15. // base case 2: we came to end in string, but pattern contains more symbols (and it is not '*')
  16. if (str.length() == 0 && !pattern.equals("*")) {
  17. return false;
  18. }
  19. // checking the next symbol matching
  20. if (charsMatch(pattern, '?') || charsMatch(pattern, str)) {
  21. return matches(pattern.substring(1), str.substring(1));
  22. }
  23. // checking wildcard - there are two scenarios: either we skip the wildcard, or we skip the next symbol
  24. if (charsMatch(pattern, '*')) {
  25. return matches(pattern.substring(1), str) || matches(pattern, str.substring(1));
  26. }
  27. return false;
  28. }
  29.  
  30. private static boolean charsMatch(String s, char ch) {
  31. return s.length() > 0 && s.charAt(0) == ch;
  32. }
  33. private static boolean charsMatch(String s, String p) {
  34. return s.length() > 0 && p.length() > 0 && s.charAt(0) == p.charAt(0);
  35. }
  36.  
  37. public static void main(String[] args) {
  38. eq("g*ks", "geeks"); // Yes
  39. eq("ge?ks*", "geeksforgeeks"); // Yes
  40. neq("g*k", "gee"); // No because 'k' is not in second
  41. neq("*pqrs", "pqrst"); // No because 't' is not in first
  42. eq("abc*bcd", "abcdhghgbcd"); // Yes
  43. neq("abc*c?d", "abcd"); // No because second must have 2 instances of 'c'
  44. eq("*c*d", "abcd"); // Yes
  45. eq("*?c*d", "abcd"); // Yes
  46. }
  47.  
  48. private static void eq(String s, String s2) {
  49. assert matches(s, s2);
  50. }
  51. private static void neq(String s, String s2) {
  52. assert !matches(s, s2);
  53. }
  54. }
Success #stdin #stdout 0.09s 320320KB
stdin
Standard input is empty
stdout
Standard output is empty