Recursive Java code


  • 0
    L
      public boolean detectCapitalUse(String word)
      {
        if (word.length() <= 1)
        {
          return true;
        }
        boolean first = Character.isUpperCase(word.charAt(0));
        boolean prev = Character.isUpperCase(word.charAt(1));
        if (!first && prev)
        {
          return false;
        }
        return helper(word, 2, first, prev);
      }
    
    
    
      private boolean helper(String word, int i, boolean first,
          boolean prev)
      {
        if (i == word.length())
        {
          return true;
        }
        boolean isUpper = Character.isUpperCase(word.charAt(i));
        if (!first && (prev || isUpper))
        {
          return false;
        }
        else if (first && (prev && !isUpper) || (!prev && isUpper))
        {
          return false;
        }
        return helper(word, i + 1, true,
            Character.isUpperCase(word.charAt(i)));
      }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.