next up previous
Next: Nested loops Up: Unit 06 Previous: GCD: using the method

Example: length of the longest subsequence

Realize a public static method that takes as parameter a string s (that is constituted only by the characters '0' and '1'), and returns the length of the longest subsequence of s constituted only by consecutive '0's.

Example: If the string passed as parameter is "001000111100", then the longest subsequence of only '0's is the underlined one, which has length 3.

public static int subsequence(String s) {
  char bit;           // current element in the sequence
  int cont = 0;       // current length of the sequence of zeros
  int maxlen = 0;     // temporary value of the maximum length

  for (int i = 0; i < s.length(); i++) {
    bit = s.charAt(i);

    if (bit == '0') {      // we have read a new '0'
      cont++;              // update the length of the current sequence
      if (cont > maxlen)   // if necessary, ...
                           // ... update the temporary maximum
        maxlen = cont;
    } else                 // we have read a 1
      cont = 0;            // reset the length of the current sequence
  }

  return maxlen;
}


next up previous
Next: Nested loops Up: Unit 06 Previous: GCD: using the method