http://acm.pku.edu.cn/JudgeOnline/problem?id=3332
实数解析,
关键是看懂这段定义:
Real numbers may have a decimal point, an exponent (starting with the character e or E), or both. Additionally, it has the usual collection of decimal digits. If there is a decimal point, there must be at least one digit on each side of the point. There may be a plus or minus sign in front of the number, or the exponent, or both (without any blank characters after the sign). Exponents are integers (not having decimal points).
关键点:如果有小数点者小数点两边至少都要有一个数。e和指数之间可以有 + — 或者都无。
Pattern pattern = Pattern.compile("\\d+(.\\d+)?([e|E]?|([e|E]([-|+]?\\d+)))?");
//Pattern pattern = Pattern.compile("\\d+(.\\d+)?([e|E]?|([e|E]([-|+]?\\d+)))?$"); 这种写法比前者慢
根据题意写出上述的表达式。
代码:
import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { //Scanner scn = new Scanner(Main.class.getResourceAsStream("in.dat")); PrintWriter out = new PrintWriter(System.out); Scanner scn = new Scanner(System.in); //Pattern pattern = Pattern.compile("\\s*(\\d+||\\d+.\\d{1,})(([e|E])?|([e|E]([-|+]?\\d+)))?"); Pattern pattern = Pattern.compile("\\s*\\d+(.\\d+)?([e|E]?|([e|E]([-|+]?\\d+)))?"); Matcher matcher; List<String> lines = new ArrayList<String>(); int n = scn.nextInt(); while(n-- != 0){ lines.add(scn.next().trim()); } n = lines.size(); matcher = pattern.matcher(lines.get(0)); for(int i = 0; i < n; i++){ matcher.reset(lines.get(i)); if(matcher.matches()){ out.println("LEGAL"); }else{ out.println("ILLEGAL"); } } out.flush(); } }
还有一种方法是在读的时候就解析,但速度没有前者快,估计是io问题:
import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { //Scanner scn = new Scanner(Main.class.getResourceAsStream("in.dat")); PrintWriter out = new PrintWriter(System.out); Scanner scn = new Scanner(System.in); //Pattern pattern = Pattern.compile("\\s*(\\d+||\\d+.\\d{1,})(([e|E])?|([e|E]([-|+]?\\d+)))?"); Pattern pattern = Pattern.compile("\\s*\\d+(.\\d+)?([e|E]?|([e|E]([-|+]?\\d+)))?"); List<String> lines = new ArrayList<String>(); int n = scn.nextInt(); scn.nextLine(); //scn.useDelimiter(pattern); while(n-- != 0){ if(scn.hasNext(pattern)){ out.println("LEGAL"); }else{ out.println("ILLEGAL"); } scn.nextLine(); //System.out.println(scn.next(pattern)); //lines.add(scn.next().trim()); } /*n = lines.size(); for(int i = 0; i < n; i++){ if(pattern.matcher(lines.get(i)).matches()){ out.println("LEGAL"); }else{ out.println("ILLEGAL"); } }*/ out.flush(); } }
PS:java速度用不如C 和 C++……