日期数组中最长的连续子序列

Sah*_*een 0 java android date jodatime

嗨我有一个按Arraylist日期顺序排列的日期.日期是这种格式yyyy-MM-dd.现在我想找出最长的连续子序列Arraylist.我已经在线检查了解决方案,但它们与int数组有关,我想查找日期数组.int数组的代码:

// Returns length of the longest contiguous subarray
int findLength(int arr[], int n)
{
int max_len = 1;  // Initialize result
for (int i=0; i<n-1; i++)
{
    // Initialize min and max for all subarrays starting with i
    int mn = arr[i], mx = arr[i];

    // Consider all subarrays starting with i and ending with j
    for (int j=i+1; j<n; j++)
    {
        // Update min and max in this subarray if needed
        mn = min(mn, arr[j]);
        mx = max(mx, arr[j]);

        // If current subarray has all contiguous elements
        if ((mx - mn) == j-i)
            max_len = max(max_len, mx-mn+1);
    }
}
return max_len;  // Return result
}

// Utility functions to find minimum and maximum of
// two elements
int min(int x, int y) { return (x < y)? x : y; }
int max(int x, int y) { return (x > y)? x : y; }
Run Code Online (Sandbox Code Playgroud)

Bas*_*que 5

TL;博士

ChronoUnit.DAYS.between ( 
    LocalDate.parse( previousString ) , 
    LocalDate.parse( currentString )
)
Run Code Online (Sandbox Code Playgroud)

字符串!=日期

我有一个Arraylist包含日期递增的日期.日期为yyyy-MM-dd格式.

这意味着你有一个ListString对象,而不是日期.这里的主要挑战是获取日期对象,以便计算它们之间的天数.

java.time

现代的方式是与取代的麻烦旧的遗留类(在java.time类Date,Calendar等等).

您的输入字符串恰好符合标准ISO 8601格式.在解析/生成字符串时,java.time类默认使用ISO 8601格式.因此无需指定格式化模式.

List<String> inputs = new ArrayList<> ();
inputs.add ( "2016-01-23" );
inputs.add ( "2016-01-25" );
inputs.add ( "2016-02-22" ); // End of longest period between dates.
inputs.add ( "2016-02-25" );
inputs.add ( "2016-02-28" );
Run Code Online (Sandbox Code Playgroud)

LocalDate级表示没有时间一天和不同时区的日期,唯一的价值.

此示例代码的策略是计算每个LocalDate(从每个传入的String解析)和前一个之间的天数LocalDate.如果长于目前为止看到的最长,请忘记旧的最长并记住当前循环的数据.

LocalDate longestStart = null;
LocalDate longestStop = null;
LocalDate previousDate = null;
long longestInDays = 0;
Run Code Online (Sandbox Code Playgroud)

枚举了一些非常方便的方法,如计算经过的天.ChronoUnit

for ( String input : inputs ) {
    LocalDate currentDate = LocalDate.parse ( input );
    if ( null == previousDate ) {  // First loop.
        previousDate = currentDate;
        continue;  // Skip the rest of this first loop.
    }
    long currentDays = ChronoUnit.DAYS.between ( previousDate , currentDate );
    if ( currentDays > longestInDays ) {
        // If the current loop exceeds previous longest, remember this one as longest.
        longestInDays = currentDays;
        longestStart = previousDate;
        longestStop = currentDate;
    }
    // Prepare for next loop.
    previousDate = currentDate;
}
Run Code Online (Sandbox Code Playgroud)

将结果转储到控制台.

System.out.println ( "Longest period has days: " + longestInDays + " = " + longestStart + "/" + longestStop );
Run Code Online (Sandbox Code Playgroud)

最长的时段有天:28 = 2016-01-25/2016-02-22

请参阅IdeOne.com中的实时代码.