zoukankan      html  css  js  c++  java
  • 809. Expressive Words

    Sometimes people repeat letters to represent extra feeling, such as "hello" -> "heeellooo", "hi" -> "hiiii".  Here, we have groups, of adjacent letters that are all the same character, and adjacent characters to the group are different.  A group is extended if that group is length 3 or more, so "e" and "o" would be extended in the first example, and "i" would be extended in the second example.  As another example, the groups of "abbcccaaaa" would be "a", "bb", "ccc", and "aaaa"; and "ccc" and "aaaa" are the extended groups of that string.

    For some given string S, a query word is stretchy if it can be made to be equal to S by extending some groups.  Formally, we are allowed to repeatedly choose a group (as defined above) of characters c, and add some number of the same character c to it so that the length of the group is 3 or more.  Note that we cannot extend a group of size one like "h" to a group of size two like "hh" - all extensions must leave the group extended - ie., at least 3 characters long.

    Given a list of query words, return the number of words that are stretchy. 

    Example:
    Input: 
    S = "heeellooo"
    words = ["hello", "hi", "helo"]
    Output: 1
    Explanation: 
    We can extend "e" and "o" in the word "hello" to get "heeellooo".
    We can't extend "helo" to get "heeellooo" because the group "ll" is not extended.
    

    Notes:

    • 0 <= len(S) <= 100.
    • 0 <= len(words) <= 100.
    • 0 <= len(words[i]) <= 100.
    • S and all words in words consist only of lowercase letters

    解法:two pointers in one pass

    遍历S中的每个字符,如果S[i] == w[j],两个指针都移动;如果不等,且S[i]接连三个字母都相同,只移动S的指针。循环W中的每个单词。

    检查3个连续字符的时候注意边界,prev, cur, next相等,移动指针,cur-2, cur-1, cur也要相等

    时间:O(N),空间:O(1)

    class Solution {
        public int expressiveWords(String S, String[] words) {
            int cnt = 0;
            for(String W : words) {
                if(W.length() > S.length()) continue;
                int i = 0, j = 0;
                for(i = 0; i < S.length(); i++) {
                    if(j < W.length() && S.charAt(i) == W.charAt(j))
                        j++;
                    else if(i > 0 && i + 1 < S.length() && S.charAt(i) == S.charAt(i+1) && S.charAt(i) == S.charAt(i-1))
                        i++;
                    else if(!(i > 1 && S.charAt(i) == S.charAt(i-1) && S.charAt(i) == S.charAt(i-2)))
                        break;
                }
                if(i == S.length() && j == W.length())
                    cnt++;
            }
            return cnt;
        }
    }
  • 相关阅读:
    set-rebgin
    HTML5开发学习:本地存储Web Sql Database
    Sublime text 入门学习资源篇及其基本使用方法
    web前端不可错过的开发工具–Adobe Brackets
    关于WEB前端开发的工具
    WebStorm使用技巧
    五大浏览器兼容性
    IT解惑真经
    win7下一劳永逸地解决触控板禁用的问题
    PHP+Mysql学习笔记
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10014529.html
Copyright © 2011-2022 走看看