|
| 1 | +// Leetcode's Detect Capital problem's solution in Dart programming language |
| 2 | +// Link to the problem: https://leetcode.com/problems/detect-capital/ |
| 3 | +// Result: Runtime: 395 ms, faster than 83.33% of Dart online submissions for Detect Capital, Memory Usage: 141.7 MB, less than 33.33% of Dart online submissions for Detect Capital. |
| 4 | +// Statement: |
| 5 | +// We define the usage of capitals in a word to be right when one of the following cases holds: |
| 6 | + // All letters in this word are capitals, like "USA". |
| 7 | + // All letters in this word are not capitals, like "leetcode". |
| 8 | + // Only the first letter in this word is capital, like "Google". |
| 9 | +// Given a string word, return true if the usage of capitals in it is right. |
| 10 | + |
| 11 | + |
| 12 | +// Solution: |
| 13 | + |
| 14 | +class Solution { |
| 15 | + bool detectCapitalUse(String word) { |
| 16 | + |
| 17 | + var capitalizedWord = word.toUpperCase(); |
| 18 | + var lowerWord = word.toLowerCase(); |
| 19 | + |
| 20 | + // a String type List to store true or false value per character to compare capitals and smalls |
| 21 | + List<String> storeToCheck = []; |
| 22 | + |
| 23 | + // Temporarily capitalizing the word to compare |
| 24 | + String nowUpperCase = word.toUpperCase(); |
| 25 | + String nowLowerCase = word.toLowerCase(); |
| 26 | + |
| 27 | + if(word.length==1){ |
| 28 | + if(word==capitalizedWord) return true; |
| 29 | + else if(word==lowerWord) return true; |
| 30 | + |
| 31 | + } else{ |
| 32 | + if(word==capitalizedWord) return true; |
| 33 | + else if(word==lowerWord) return true; |
| 34 | + for(int i=1; i<word.length; i++) { |
| 35 | + if(isUpperCase(word[0]) && (isLowerCase(word[i]))){ |
| 36 | + storeToCheck.add("true"); |
| 37 | + } |
| 38 | + else{ |
| 39 | + storeToCheck.add("false"); |
| 40 | + } |
| 41 | + |
| 42 | +} |
| 43 | + } |
| 44 | + |
| 45 | + return (storeToCheck.contains("false")) ? false : true; |
| 46 | + } |
| 47 | + // custom function to check lowercase letters |
| 48 | + bool isLowerCase(String str) { |
| 49 | + return str == str.toLowerCase(); |
| 50 | +} |
| 51 | + // custom function to check uppercase letters |
| 52 | + bool isUpperCase(String str){ |
| 53 | + return str==str.toUpperCase(); |
| 54 | + } |
| 55 | +} |
0 commit comments