本文共 3237 字,大约阅读时间需要 10 分钟。
问题描述:给定一些字符串表示学生的出勤记录。
例如:PPALLP 其中 A 表示Absent;L表示 Late;P表示 Present。 学生获得表彰的条件是出勤记录中不能存在A,或者两个以上(不含两个)的L。 请写一个算法,分析给定的出勤记录,判断学生是否能够获得表彰。算法设计:
package com.bean.basic;public class StudentAttendanceRecordDemo2 { /* * You are given a string representing an attendance record for a student. * The record only contains the following three characters: * 1.'A' : Absent. * 2.'L' : Late. * 3.'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. * * Example 1: * Input: "PPALLP" * Output: True * * Example 2: * Input: "PPALLL" * Output: False * * */ /* * Solution 1(解法 1) * */// public static boolean checkRecord(String s) { // int a = 0, l = 0;// char p = 'N';// for(char c: s.toCharArray()){ // if(c == 'A') { // a++; // if(a > 1) return false;// }// if(c == 'L'){ // if(p == 'L'){ // l++; // if(l > 2) return false;// }else{ // l = 1; // }// }// p = c;// }// // return true;// } /* * Solution 2(解法 2) * */// public static boolean checkRecord(String s) // { // if (s.contains("LLL")) return false;// // String str = s.replaceAll("A", "");// // if ((s.length() - str.length()) > 1)// { // return false;// }// // // return true;// // } /* * Solution 3 (解法 3) * */// public static boolean checkRecord(String s) { // if(s.indexOf("A") != s.lastIndexOf("A") || ( s.contains("LLL"))) // return false;// return true;// } /* * Solution 4 (解法 4) * */// public static boolean checkRecord(String s) { // return !s.matches(".*A.*A.*") && !s.matches(".*LLL.*");// } /* * Solution 5 (解法 5) * */ public static boolean checkRecord(String s) { //Time ~ O(n) //Space ~ O(1) // ---> where n is the length of String s int countA = 0; int countL = 0; for(int i = 0; i < s.length(); i++){ if(s.charAt(i) == 'A'){ if(countA == 1){ return false; } else{ countA = countA + 1; } countL = 0; } else if(s.charAt(i) == 'L'){ if(countL == 2){ return false; } else{ countL = countL + 1; } } else{ countL = 0; } } return true; } public static void main(String[] args) { // TODO Auto-generated method stub //String str="PPALLL"; String str="PPALLP"; boolean flag=checkRecord(str); if(flag) { System.out.println("TRUE"); }else { System.out.println("FALSE"); } }}
(完)
转载地址:http://fgvdi.baihongyu.com/