Phil DiMarco
Phil DiMarco

Reputation: 51

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. If no valid String is found the method should return -1

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 Solution2 {
public int solution(String S) {
    int first = 0;
    int last = S.length()-1;
    int longest = -1;
    for(int i = 0; i < S.length(); i++){
        if(Character.isUpperCase(S.charAt(i))){
        first = i;
        last = first;
        while(last < S.length()){
                 if(Character.isDigit(S.charAt(last))){
                    i = last;
                    break;
                    }
                 last++;
            }    
        longest = Math.max(last - first, longest);
        }
     }
    return longest;    
 }
}

added updated solution, any thoughts to optimize this further?

Upvotes: 0

Views: 2663

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Your solution is too complicated. Since you are not asked to find the longest password, only the length of the longest password, there is no reason to create or store strings with that longest password. Therefore, you do not need to use substring or an array of Strings, only int variables.

The algorithm for finding the solution is straightforward:

  1. Make an int pos = 0 variable representing the current position in s
  2. Make a loop that searches for the next candidate password
  3. Starting at position pos, find the next uppercase letter
  4. If you hit the end of line, exit
  5. Starting at the position of the uppercase letter, find the next digit
  6. If you hit the end of line, stop
  7. Find the difference between the position of the digit (or the end of line) and the position of the uppercase letter.
  8. If the difference is above max that you have previously found, replace max with the difference
  9. Advance pos to the position of the last letter (or the end of line)
  10. If pos is under s.length, continue the loop at step 2
  11. Return max.

Demo.

Upvotes: 1

Related Questions