[LintCode] Twitch Words

 约 4 分钟

Problem

Our normal words do not have more than two consecutive letters. If there are three or more consecutive letters, this is a tics. Now give a word, from left to right, to find out the starting point and ending point of all tics.

Example

Given str = "whaaaaatttsup", return [[2,6],[7,9]].

Explanation:
"aaaa" and "ttt" are twitching letters, and output their starting and ending points.
Given str = "whooooisssbesssst", return [[2,5],[7,9],[12,15]].

Explanation:
"ooo", "sss" and "ssss" are twitching letters, and output their starting and ending points.

Solution


public class Solution {
    /**
     * @param str: the origin string
     * @return: the start and end of every twitch words
     */
    public int[][] twitchWords(String str) {
        //set two boundaries, one pre value, only move the right boundary
        List<List<Integer>> res = new ArrayList<>();
        int l = 0, r = 0;
        char[] strs = str.toCharArray();
        char pre = strs[0];
        for (int i = 0; i < strs.length; i++) {
            List<Integer> cur = new ArrayList<>();
            if (i != 0 && strs[i] != pre) {
                if (r-l >= 2) {
                    cur.add(l);
                    cur.add(r);
                    res.add(cur);
                }
                l = i;
                r = i;
                pre = strs[i];
            } else if (strs[i] == pre) {
                r = i;
            }
        }
        //when the last three chars are twitch
        if (r-l >= 2) {
            List<Integer> cur = new ArrayList<>();
            cur.add(l);
            cur.add(r);
            res.add(cur);
        }
        
        int[][] ans = new int[res.size()][2];
        for (int i = 0; i < res.size(); i++) {
            ans[i][0] = res.get(i).get(0);
            ans[i][1] = res.get(i).get(1);
        }
        return ans;
    }
}
阅读 1.1k

推荐阅读
Road to Glory
用户专栏

對酒當歌,人生幾何?譬如朝露,去日苦多。

22 人关注
639 篇文章
专栏主页
目录