fares's blog

By fares, history, 11 years ago, In English

hi guys: i solved this problem : http://codeforces.me/problemset/problem/58/A

then i saw a code that an orange user used to solve it , here is the code: import java.util.Scanner; public class Main{

     public static void main(String[] args) throws Exception {
         Scanner in = new Scanner(System.in);

         String[] str = in.nextLine().split(".*h.*e.*l.*l.*o.*");
         System.out.println(str.length == 0 ? "YES" : "NO");

     }

}

i understand that the split method splits the String when it finds the String parameter given to it , then it puts the substrings
into the array . but what is all the "." and "*" do? what does this code do?

  • Vote: I like it
  • -5
  • Vote: I do not like it

»
11 years ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

Let me guess that this is regex. *c will match all characters until c is found. That means in string "ahellou", "*h" will match "ah". And '.' means concatenation. So the pattern means, find match where after some or 0 characters there's 'h', after that after some or 0 character there's e, etc. At last, * means capture the rest of the characters also.(Pardon my Java code... I rarely code in Java)

import java.util.Scanner;
public class Main {
  public static void main(String[] args) throws Exception {
    Scanner in = new Scanner(System.in);
    String[] str = mySplit(in.nextLine());
    System.out.println(str.length == 0 ? "YES" : "NO");
  }
  private static int matchUntilChar(String line, int i, char c) {
    while(i < line.length() && line.charAt(i) != c) i++;
    // not found
    if(i == line.length()) return -1;
    else return i+1;
  }
  private static String[] mySplit(String line) {
    String[] notFound = new String[] { line };
    int i = 0;
    for(char c : new char[]{'h','e','l','l','o'}) {
      i = matchUntilChar(line, i, c);
      if(i == -1) return notFound;
    }
    return new String[]{}; // empty string denotes found
  }
}