[LintCode] Twitch Words

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> 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 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 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;
    }
}

你可能感兴趣的:(数组,arraylist,LintCode,java)