dimanche 18 octobre 2015

Java Searching through a String for a valid character sequence

I just took a codility test and was wondering why my solution only scored 37/100. The problem was that you were given a String and had to search through it for valid passwords. Here are the rules:

1) A valid password starts with a capital letter and cannot contain any numbers. The input is restricted to any combination of a-z, A-Z and 0-9.

2)The method they wanted you to create is suppose to return the size of the largest valid password. So for example if you input "Aa8aaaArtd900d" the number 4 is suppose to be outputted by the solution method.

I cannot seem to figure out where I went wrong in my solution. Any help would be greatly appreciated! Also any suggestions on how to better test code for something like this would be greatly appreciated.

class Solution {
public int solution(String S) {
    String[] passwords = new String[S.length()];
    int count = 0;
    int first = 0;
    int last = S.length()-1;

    for(int i = 0; i < S.length(); i++){
        if(Character.isUpperCase(S.charAt(i))){
        first = i;
        int p = first;

        boolean numNotFound = true;
        while(p < S.length() && numNotFound){
                 if(Character.isDigit(S.charAt(p))){
                    last = p;
                    i = p;
                    numNotFound = false;
                    }
                    p++;
                    if(numNotFound){last = p;}
            }    
        System.out.println(first + " " + last);
        passwords[count] = S.substring(first,last);
        count++;
        }
        }

        int longestPassword = -1;
        for(int x = 0; x < count; x++){
        if(longestPassword < passwords[x].length()){
            System.out.println(passwords[x]);
            longestPassword = passwords[x].length();
            }
        }
        return longestPassword;
  }
}   

Aucun commentaire:

Enregistrer un commentaire