最長連續降序數字子串

import java.util.ArrayList;
import java.util.List;

public class LongestConsecutiveDescendingNumberSubstring
{

    public static void main(String[] args)
    {
        System.out.println(longestConsecutiveDescendingNumberSubstring("s")); // []
        System.out.println(longestConsecutiveDescendingNumberSubstring("3")); // [3]
        System.out.println(longestConsecutiveDescendingNumberSubstring("3s7")); // [3, 7]
        System.out.println(longestConsecutiveDescendingNumberSubstring("421")); // [21]
        System.out.println(longestConsecutiveDescendingNumberSubstring("5a321")); // [321]
        System.out.println(longestConsecutiveDescendingNumberSubstring("4433210")); // [3210]
        System.out.println(longestConsecutiveDescendingNumberSubstring("44332103210"));// [3210, 3210]
    }

    public static List<String> longestConsecutiveDescendingNumberSubstring(String s)
    {
        List<String> list = new ArrayList<String>();
        if (s == null || s.length() == 0)
        {
            return list;
        }
        char pre = s.charAt(0);
        int count = 1, max = 1;
        for (int i = 1; i < s.length(); i++)
        {
            char cur = s.charAt(i);
            if (Character.isDigit(pre) && Character.isDigit(cur) && pre - 1 == cur)
            {
                count++;
                max = Math.max(count, max);
            }
            else
            {
                count = 1;
            }
            pre = cur;
        }
        if (max == 1)
        {
            for (int i = 0; i < s.length(); i++)
            {
                char c = s.charAt(i);
                if (Character.isDigit(c))
                {
                    list.add(String.valueOf(c));
                }
            }
            return list;
        }
        count = 1;
        List<Integer> indexList = new ArrayList<Integer>();
        for (int i = 1; i < s.length(); i++)
        {
            char cur = s.charAt(i);
            if (Character.isDigit(pre) && Character.isDigit(cur) && pre - 1 == cur)
            {
                count++;
                if (count == max)
                {
                    indexList.add(i - max + 1);
                }
            }
            else
            {
                count = 1;
            }
            pre = cur;
        }
        for (int i = 0; i < indexList.size(); i++)
        {
            int begin = indexList.get(i);
            list.add(s.substring(begin, begin + max));
        }
        return list;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章