Answers for "leetcode 809"

0

leetcode 809

class Solution {
    public int expressiveWords(String s, String[] words) {
        String rleKey = rle(s);
        
        int ans = 0;
        
        for(String word: words) {
            String rleWord = rle(word);
            if(rleKey.length() != rleWord.length()) {
                continue;
            }
            if(isStretchy(rleWord, rleKey)) {
                ans++;
            }
        }
        
        return ans;
    }
    
    private String rle(String s) {
        StringBuilder sb = new StringBuilder();
        int count = 0;
        char ch = s.charAt(0);
        
        for(int i=0; i<s.length(); i++) {
            if(ch == s.charAt(i)) {
                count++;
            } else {
                sb.append(ch);
                sb.append(count);
                count=1;
                ch = s.charAt(i);
            }
        }
        
        sb.append(ch);
        sb.append(count);
        
        return sb.toString();        
    }
    
    private boolean isStretchy(String word, String key) {
        for(int i=0; i<word.length(); i+=2) {
            char wordChar = word.charAt(i);
            int count = word.charAt(i+1)-'0';
            
            char keyChar = key.charAt(i);
            int keyCount = key.charAt(i+1)-'0';
            
            if(wordChar != keyChar ||
               count > keyCount ||
               (keyCount < 3 && count != keyCount)) {
                return false;
            }
            
        }
        
        return true;
    }
}
Posted by: Guest on January-11-2022

Browse Popular Code Answers by Language