LeetCode练习<三> 找出字符串中连续的字母

来源:互联网 发布:tc编程怎么收费 编辑:程序博客网 时间:2024/05/29 15:48

题目如下:

/** * You are given a string representing an attendance record for a student. The record only contains the * following three characters: *      'A' : Absent. *      'L' : Late. *      'P' : Present. * A student could be rewarded if his attendance record doesn't contain more than one 'A' (absent) or * more than two continuous 'L' (late). * You need to return whether the student could be rewarded according to his attendance record. * Created by greg on 17-4-16. */
 

就是如如一个字符串,判断字符串中是否有超过一个A或者超过连续2个L,(也就是题目中说的包含超过一个A或者超过连续2个L),由以上的情况就返回false,没有就返回true.

一开始没有想到用正则化,打算用StringBuilder,挨个判断,但是忽略了连续二字.最后想到这就是个匹配问题,既然是匹配,那就用正则化.

上代码:

                                                                              /**                                                                        * 正则表达式:                                                                  * . 表示任意一个字符                                                              * * 表示0个或任意多个字符                                                           * .*LLL.* 表示在LLL的前后可以有任意一个或多个字符,只要保证LLL连续就行                               * .*A.*A.*A 表示在A的前后可以有任意一个或多个字符,只要保证字符串中出现两个A就行                           * @param s                                                                * @return                                                                 */                                                                       public static boolean checkRecord1(String s) {                        //        return s.matches(".*LLL.*|.*A.*A.*");                                   return !s.matches(".*[L]{3}.*|.*A.*A.*");                             }                                                                     
 

在使用正则表达式的时候:我们的目的是找到是否有1个以上A(只要有两个就可以), 或者2个以上连续L(只要有3个连续的L)就可以. 所以说,目标很明确.注意在使用正则化的时候,是匹配的整个字符串,并不仅仅是我们要找的目标, 所以我们要使用"."   ,   "*" 来表示我们目标之外的字符.如果只是用s.matches("[L]{3}"), 那就相当于匹配s是否为"LLL"了.

0 0