简单算法3
Posted fmgao-technology
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简单算法3相关的知识,希望对你有一定的参考价值。
股票
package com.sly.uploadfile.algorithm; /** * Created by fmgao on 2019/7/9. * 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 * <p> * 如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。 * <p> * 注意你不能在买入股票前卖出股票。 * <p> * 示例 1: * <p> * 输入: [7,1,5,3,6,4] * 输出: 5 * 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。 * 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。 */ public class Gupiao01 { public static int maxProfit(int[] prices) { if (prices == null || prices.length == 0) { return 0; } int[] dp = new int[prices.length]; int minPrice = prices[0]; for (int i = 1; i < prices.length; i++) { minPrice = Math.min(minPrice, prices[i]); dp[i] = Math.max(dp[i - 1], prices[i] - minPrice);//只需记住当前的最小值即可 } return dp[prices.length - 1]; } public static void main(String[] args) { int[] a = {7, 1, 5, 3, 6, 4}; int d = maxProfit(a); System.out.println(d); System.out.println(getMax(a)); } public static int getMax(int[] a) { if (a.length == 0 || a == null) { return 0; } int b[] = new int[a.length]; int mina = a[0]; for (int i = 1; i < a.length; i++) { mina = Math.min(mina, a[i]); b[i] = Math.max(b[i - 1], a[i] - mina); } return b[a.length - 1]; } }
括号分数
package com.sly.uploadfile.algorithm; import java.util.Stack; /** * Created by fmgao on 2019/9/11. * 给定一个平衡括号字符串 S,按下述规则计算该字符串的分数: * <p> * () 得 1 分。 * AB 得 A + B 分,其中 A 和 B 是平衡括号字符串。 * (A) 得 2 * A 分,其中 A 是平衡括号字符串。 * <p> * <p> * 示例 1: * <p> * 输入: "()" * 输出: 1 */ public class KuoHaoFenShu { public static void main(String[] args) { System.out.println(scoreOfParent("((()))")); } public static int scoreOfParent(String s) { Stack<String> stack = new Stack<>(); for (int i = 0, len = s.length(); i < len; i++) { if (‘(‘ == s.charAt(i)) { stack.push("("); } else { if ("(".equals(stack.peek())) { stack.pop(); stack.push(1 + ""); } else { int intTemp = Integer.parseInt(stack.pop()); if ("(".equals(stack.peek())) { stack.pop(); stack.push((intTemp * 2) + ""); } } // 如果栈里面的元素有多个数字的情况,那么你就需要把这几个数字进行相加,然后再压入栈 int add = 0; while (!stack.isEmpty() && !"(".equals(stack.peek())) { add += Integer.parseInt(stack.pop()); } stack.push(add + ""); } } return Integer.parseInt(stack.pop()); } }
字符串长度
package com.sly.uploadfile.algorithm; /** * Created by fmgao on 2020/1/7. */ public class LengthOfString { public static void main(String[] args) { String a = "i am a person"; System.out.println(getLength(a)); System.out.println(getLength1(a)); } private static int getLength(String s) { if (s == "") { return 0; } if (s.trim().length() == 0) { return 0; } String[] a = s.split(" "); return a[a.length - 1].length(); } private static int getLength1(String s) { int len = s.length(); while (len > 0 && s.substring(len - 1, len).equals(" ")) { len--; } for (int i = len - 1; i >= 0; i--) { if (s.substring(i, i + 1).equals(" ")) { return len - 1 - i; } } return len; } }
重复数组移除重复数据后的长度
package com.sly.uploadfile.algorithm; /** * Created by fmgao on 2019/12/9. * <p> * 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。 * 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。 * <p> * 示例 1: * 给定数组 nums = [1,1,2], * 函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 * 你不需要考虑数组中超出新长度后面的元素。 */ public class RemoveDuplicates { public static void main(String[] args) { int[] nums = {1, 1, 2, 2, 3, 3, 3, 4, 4}; // int i = removeDuplicates(nums); // System.out.println(i); System.out.println(removeDuplicates(nums)); } public static int removeDuplicates(int[] nums) { if (nums.length == 0) { return 0; } int i = 0; for (int j = 1; j < nums.length; j++) { if (nums[j] != nums[i]) { i++; nums[i] = nums[j]; } } return i + 1; } public static int removeDuplicates2(int[] nums) { if (nums.length <= 1) { return nums.length; } int cur = 1; for (int j = 1; j < nums.length; j++) { if (nums[j] != nums[cur - 1]) { nums[cur++] = nums[j]; } } return cur; } public static int removeDuplicates3(int[] nums) { if (nums.length <= 2) { return nums.length; } int num = 1; int cur = 1; for (int i = 1; i < nums.length; i++) { if (nums[i] == nums[i - 1]) { if (num == 1) { nums[cur++] = nums[i]; } num++; } else { nums[cur++] = nums[i]; num = 1; } } return cur; } }
数字resverse
package com.sly.uploadfile.algorithm; /** * Created by fmgao on 2019/7/1. */ public class ReverseIntNo { public static void main(String[] args) { int res = reverse(147483647); System.out.println(res); System.out.println(Integer.MAX_VALUE); System.out.println(147483647 % 10); System.out.println(147483647 / 10); } public static int reverse(int x) { long result = 0; while (x != 0) { result = result * 10 + x % 10; x /= 10; } if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) { result = 0; } return (int) result; } }
字符串转整数
package com.sly.uploadfile.algorithm; /** * Created by fmgao on 2019/9/19. */ /** * 字符串转整数(atoi) * <p> * 实现 atoi,将字符串转为整数。 * <p> * 在找到第一个非空字符之前,需要移除掉字符串中的空格字符。如果第一个非空字符是正号或负号,选取该符号,并将其与后面尽可能多的连续的数字组合起来,这部分字符即为整数的值。如果第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成整数。 * <p> * 字符串可以在形成整数的字符后面包括多余的字符,这些字符可以被忽略,它们对于函数没有影响。 * <p> * 当字符串中的第一个非空字符序列不是个有效的整数;或字符串为空;或字符串仅包含空白字符时,则不进行转换。 * <p> * 若函数不能执行有效的转换,返回 0。 * <p> * 说明: * <p> * 假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231, 231 − 1]。如果数值超过可表示的范围,则返回 INT_MAX (231 − 1) 或 INT_MIN (−231) 。 * <p> * 示例 1: * <p> * 输入: "42" * 输出: 42 * <p> * 示例 2: * <p> * 输入: " -42" * 输出: -42 * 解释: 第一个非空白字符为 ‘-‘, 它是一个负号。 * 我们尽可能将负号与后面所有连续出现的数字组合起来,最后得到 -42 。 * <p> * 示例 3: * <p> * 输入: "4193 with words" * 输出: 4193 * 解释: 转换截止于数字 ‘3‘ ,因为它的下一个字符不为数字。 * <p> * 示例 4: * <p> * 输入: "words and 987" * 输出: 0 * 解释: 第一个非空字符是 ‘w‘, 但它不是数字或正、负号。 * 因此无法执行有效的转换。 * <p> * 示例 5: * <p> * 输入: "-91283472332" * 输出: -2147483648 * 解释: 数字 "-91283472332" 超过 32 位有符号整数范围。 * 因此返回 INT_MIN (−231) 。 */ public class StringToNum { public static void main(String[] args) { int res = myAtoi(" -357dhfjdk"); System.out.println(res); } public static int myAtoi(String str) { int length = str.length(); int index = 0; //先找到第一个非空的index while (index < length) { if (str.charAt(index) == ‘ ‘) { index++; } else { break; } } if (index == length) { return 0; } char now = str.charAt(index); int num = 0; //num要乘以isPositive int isPositive = 1; //去掉异常情况 if (now != ‘+‘ && now != ‘-‘ && (now > ‘9‘ || now < ‘0‘)) { return 0; } if (now == ‘+‘) { index++; } if (now == ‘-‘) { isPositive = -1; index++; } // -2147483648 2147483647 int maxValue_10 = Integer.MAX_VALUE / 10; int minValue_10 = Integer.MIN_VALUE / 10; while (index < length) { now = str.charAt(index); if (now > ‘9‘ || now < ‘0‘) { break; } int nowNum = now - ‘0‘; if (num > maxValue_10 || (num == maxValue_10 && nowNum > 7)) { num = Integer.MAX_VALUE; break; } if (num < minValue_10 || (num == minValue_10 && nowNum > 8)) { num = Integer.MIN_VALUE; break; } num = num * 10 + nowNum * isPositive; index++; } return num; } }
无重复字符串最长字串
package com.sly.uploadfile.algorithm; import java.util.LinkedList; /** * Created by fmgao on 2019/9/2. * 给定一个字符串,找出不含有重复字符的最长子串的长度。 * <p> * 示例: * <p> * 给定 "abcabcbb" ,没有重复字符的最长子串是 "abc" ,那么长度就是3。 * <p> * 给定 "bbbbb" ,最长的子串就是 "b" ,长度是1。 * <p> * 给定 "pwwkew" ,最长子串是 "wke" ,长度是3。请注意答案必须是一个子串,"pwke" 是 子序列 而不是子串 */ public class Wucongfuzifuzuichangzichuan { public static void main(String[] args) { String s = "12345665432179456789"; System.out.println(lengthOfLongestSubstring(s)); } public static int lengthOfLongestSubstring(String s) { int num = 0; int current = 0; char[] arr = s.toCharArray(); LinkedList<Character> temp = new LinkedList<>(); for (int i = 0; i < arr.length; i++) { if (!temp.contains(arr[i])) { temp.add(arr[i]); current = temp.size(); if (current > num) { num = current; } } else { //如果新增字符与原子串中字符有重复的,删除原子串中重复字符及在它之前的字符,与新增字符组成新的子串 temp.add(arr[i]); int first = temp.indexOf(arr[i]); for (int j = 0; j < first; j++) { temp.remove(); } temp.remove(); } } return num; } }
最长回文子串
package com.sly.uploadfile.algorithm; /** * Created by admin on 2020/6/10. */ public class ZuiChangHuiWenZiChuan { public static void main(String[] args) { System.out.println(longestPalindrome("12345665432179456789")); System.out.println(longestPalindrome2("12345665432179456789")); } /** * 方法一:动态规划 * 定义P(i,j):如果字符串从i位置到j位置是回文,P(i,j)=true;否则,P(i,j)=false; * 那么P(i,j)= P(i+1,j−1) && Si==Sj * 首先初始化一字母和二字母的回文: * P(i,i)=true P(i, i) = true P(i,i)=true * P(i,i+1)=(Si==Si+1) * 然后找到所有三字母回文,并依此类推… * 复杂度分析 * 时间复杂度:O(n2) * 空间复杂度:O(n2), 该方法使用 O(n2) 的空间来存储表。 * * @param s * @return */ public static String longestPalindrome(String s) { if (s == null || s.length() <= 1) { return s; } int len = s.length(); //flag[i][j]=true 表示子串i-j为回文字符串 boolean[][] flags = new boolean[1000][1000]; int start = 0; int maxlen = 0; for (int i = 0; i < len; i++) { flags[i][i] = true; if (maxlen == 0 || maxlen == 1) { start = i; maxlen = 1; } //相邻的两个字符相同 if (i < len - 1 && s.charAt(i) == s.charAt(i + 1)) { flags[i][i + 1] = true; start = i; maxlen = 2; } } //m代表回文子串长度,从3开始 for (int m = 3; m <= len; m++) { for (int i = 0; i <= len - m; i++) { //依次比较是否符合状态转移方程 int j = i + m - 1; if (flags[i + 1][j - 1] && s.charAt(i) == s.charAt(j)) { flags[i][j] = true; start = i; maxlen = m; } } } return s.substring(start, start + maxlen); } /** * 方法二:中心扩展算法 * 事实上,只需使用恒定的空间,我们就可以在 O(n2)的时间内解决这个问题。 * 回文中心的两侧互为镜像。因此,回文可以从它的中心展开 * * @param s * @return */ public static String longestPalindrome2(String s) { if (s == null || s.length() < 1) { return ""; } int start = 0; int end = 0; for (int i = 0; i < s.length(); i++) { int len1 = expandAroundCenter(s, i, i); int len2 = expandAroundCenter(s, i, i + 1); int len = Math.max(len1, len2); if (len > end - start) { start = i - (len - 1) / 2; end = i + len / 2; } } return s.substring(start, end + 1); } private static int expandAroundCenter(String s, int left, int right) { int L = left, R = right; while (L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R)) { L--; R++; } return R - L - 1; } }
package com.util.companywork; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * Created by fmgao on 2019/8/31. */ public class DateThisTest { private int x; // 日期属性:年 private int y; // 日期属性:月 private int z; // 日期属性:日 private Calendar localTime; // 当前日期 public DateThisTest() { localTime = Calendar.getInstance(); } public static Calendar getCalendarByStr(String s) { Calendar calendar = Calendar.getInstance(); try { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date date = format.parse(s); calendar = Calendar.getInstance(); calendar.setTime(date); return calendar; } catch (ParseException e) { return calendar; } } /** * 功能:得到当前日期 格式为:xxxx-yy-zz (eg: 2007-12-05)<br> * * @return String * @author pure */ public String today() { String strY = null; String strZ = null; x = localTime.get(Calendar.YEAR); y = localTime.get(Calendar.MONTH) + 1; z = localTime.get(Calendar.DATE); strY = y >= 10 ? String.valueOf(y) : ("0" + y); strZ = z >= 10 ? String.valueOf(z) : ("0" + z); return x + "-" + strY + "-" + strZ; } public String yestaday() { String strY = null; String strZ = null; x = localTime.get(Calendar.YEAR); y = localTime.get(Calendar.MONTH) + 1; z = localTime.get(Calendar.DATE) - 1; strY = y >= 10 ? String.valueOf(y) : ("0" + y); strZ = z >= 10 ? String.valueOf(z) : ("0" + z); return x + "-" + strY + "-" + strZ; } public String yestaday2() { Date today = new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); return simpleDateFormat.format(today); } public String yestaday2(String s) { try { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date today = new Date(simpleDateFormat.parse(s).getTime() - 1000 * 60 * 60 * 24); String yesterday = simpleDateFormat.format(today); return yesterday; } catch (Exception e) { return null; } } // 上周一 public String lastWeekMondayPre() { String strY = null; String strZ = null; x = localTime.get(Calendar.YEAR); y = localTime.get(Calendar.MONTH) + 1; z = localTime.get(Calendar.DATE) - 8; strY = y >= 10 ? String.valueOf(y) : ("0" + y); strZ = z >= 10 ? String.valueOf(z) : ("0" + z); return x + "-" + strY + "-" + strZ; } /** * 功能:得到当前月份月初 格式为:xxxx-yy-zz (eg: 2007-12-01)<br> * * @return String * @author pure */ public String thisMonth() { String strY = null; x = localTime.get(Calendar.YEAR); y = localTime.get(Calendar.MONTH) + 1; strY = y >= 10 ? String.valueOf(y) : ("0" + y); return x + "-" + strY + "-01"; } public String thisMonth(String s) { Calendar rr = getCalendarByStr(s); String strY = null; x = rr.get(rr.YEAR); y = rr.get(rr.MONTH) + 1; strY = y >= 10 ? String.valueOf(y) : ("0" + y); return x + "-" + strY + "-01"; } public String nextMonth() { String strY = null; x = localTime.get(Calendar.YEAR); y = localTime.get(Calendar.MONTH) + 2; strY = y >= 10 ? String.valueOf(y) : ("0" + y); return x + "-" + strY + "-01"; } public String nextMonth(String s) { Calendar rr = getCalendarByStr(s); String strY = null; x = rr.get(rr.YEAR); y = rr.get(rr.MONTH) + 2; if (y > 12) { y = y - 12; x = x + 1; } strY = y >= 10 ? String.valueOf(y) : ("0" + y); return x + "-" + strY + "-01"; } public String nextMonth2(String s) { Calendar rr = getCalendarByStr(s); String strY = null; x = rr.get(rr.YEAR); y = rr.get(rr.MONTH) + 3; if (y > 12) { y = y - 12; x = x + 1; } strY = y >= 10 ? String.valueOf(y) : ("0" + y); return x + "-" + strY + "-01"; } /** * 功能:得到当前月份月初 格式为:xxxx-yy-zz (eg: 2007-12-01)<br> * * @return String * @author pure */ public String preMonth() { String strY = null; x = localTime.get(Calendar.YEAR); y = localTime.get(Calendar.MONTH) + 0; strY = y >= 10 ? String.valueOf(y) : ("0" + y); return x + "-" + strY + "-01"; } /** * 功能:得到当前月份前月初 格式为:xxxx-yy-zz (eg: 2007-12-01)<br> * * @return String * @author pure */ public String preMonth(String s) { Calendar rr = getCalendarByStr(s); String strY = null; x = rr.get(rr.YEAR); y = rr.get(rr.MONTH); if (y < 1) { y = 12; x = x - 1; } strY = y >= 10 ? String.valueOf(y) : ("0" + y); return x + "-" + strY + "-01"; } public String preMonthEnd() { String strY = null; String strZ = null; boolean leap = false; x = localTime.get(Calendar.YEAR); y = localTime.get(Calendar.MONTH); if (y == 1 || y == 3 || y == 5 || y == 7 || y == 8 || y == 10 || y == 12) { strZ = "31"; } if (y == 4 || y == 6 || y == 9 || y == 11) { strZ = "30"; } if (y == 2) { leap = leapYear(x); if (leap) { strZ = "29"; } else { strZ = "28"; } } strY = y >= 10 ? String.valueOf(y) : ("0" + y); return x + "-" + strY + "-" + strZ; } public String preMonthEnd(String s) { Calendar rr = getCalendarByStr(s); String strY = null; String strZ = null; boolean leap = false; x = rr.get(rr.YEAR); y = rr.get(rr.MONTH); if (y < 1) { y = 12; x = x - 1; } if (y == 1 || y == 3 || y == 5 || y == 7 || y == 8 || y == 10 || y == 12) { strZ = "31"; } if (y == 4 || y == 6 || y == 9 || y == 11) { strZ = "30"; } if (y == 2) { leap = leapYear(x); if (leap) { strZ = "29"; } else { strZ = "28"; } } strY = y >= 10 ? String.valueOf(y) : ("0" + y); return x + "-" + strY + "-" + strZ; } /** * 功能:得到当前月份月底 格式为:xxxx-yy-zz (eg: 2007-12-31)<br> * * @return String * @author pure */ public String thisMonthEnd() { String strY = null; String strZ = null; boolean leap = false; x = localTime.get(Calendar.YEAR); y = localTime.get(Calendar.MONTH) + 1; if (y == 1 || y == 3 || y == 5 || y == 7 || y == 8 || y == 10 || y == 12) { strZ = "31"; } if (y == 4 || y == 6 || y == 9 || y == 11) { strZ = "30"; } if (y == 2) { leap = leapYear(x); if (leap) { strZ = "29"; } else { strZ = "28"; } } strY = y >= 10 ? String.valueOf(y) : ("0" + y); return x + "-" + strY + "-" + strZ; } /** * 功能:得到当前月份月底 格式为:xxxx-yy-zz (eg: 2007-12-31)<br> * * @return String * @author pure */ public String thisMonthEnd(String s) { Calendar rr = getCalendarByStr(s); String strY = null; String strZ = null; boolean leap = false; x = rr.get(rr.YEAR); y = rr.get(rr.MONTH) + 1; if (y == 1 || y == 3 || y == 5 || y == 7 || y == 8 || y == 10 || y == 12) { strZ = "31"; } if (y == 4 || y == 6 || y == 9 || y == 11) { strZ = "30"; } if (y == 2) { leap = leapYear(x); if (leap) { strZ = "29"; } else { strZ = "28"; } } strY = y >= 10 ? String.valueOf(y) : ("0" + y); return x + "-" + strY + "-" + strZ; } /** * 功能:得到当前月份下个月底 格式为:xxxx-yy-zz (eg: 2007-12-31)<br> * * @return String * @author pure */ public String thisNextMonthEnd() { String strY = null; String strZ = null; boolean leap = false; x = localTime.get(Calendar.YEAR); y = localTime.get(Calendar.MONTH) + 2; if (y == 1 || y == 3 || y == 5 || y == 7 || y == 8 || y == 10 || y == 12) { strZ = "31"; } if (y == 4 || y == 6 || y == 9 || y == 11) { strZ = "30"; } if (y == 2) { leap = leapYear(x); if (leap) { strZ = "29"; } else { strZ = "28"; } } strY = y >= 10 ? String.valueOf(y) : ("0" + y); return x + "-" + strY + "-" + strZ; } /** * 功能:得到当前月份下个月底 格式为:xxxx-yy-zz (eg: 2007-12-31)<br> * * @return String * @author pure */ public String thisNextMonthEnd(String s) { Calendar rr = getCalendarByStr(s); String strY = null; String strZ = null; boolean leap = false; x = rr.get(rr.YEAR); y = rr.get(rr.MONTH) + 2; if (y > 12) { y = y - 12; x = x + 1; } if (y == 1 || y == 3 || y == 5 || y == 7 || y == 8 || y == 10 || y == 12) { strZ = "31"; } if (y == 4 || y == 6 || y == 9 || y == 11) { strZ = "30"; } if (y == 2) { leap = leapYear(x); if (leap) { strZ = "29"; } else { strZ = "28"; } } strY = y >= 10 ? String.valueOf(y) : ("0" + y); return x + "-" + strY + "-" + strZ; } /** * 功能:得到当前月份三个个月底 格式为:xxxx-yy-zz (eg: 2007-12-31)<br> * * @return String * @author pure */ public String thisThreeMonthEnd(String s) { Calendar rr = getCalendarByStr(s); String strY = null; String strZ = null; boolean leap = false; x = rr.get(rr.YEAR); y = rr.get(rr.MONTH) + 3; if (y > 12) { y = y - 12; x = x + 1; } if (y == 1 || y == 3 || y == 5 || y == 7 || y == 8 || y == 10 || y == 12) { strZ = "31"; } if (y == 4 || y == 6 || y == 9 || y == 11) { strZ = "30"; } if (y == 2) { leap = leapYear(x); if (leap) { strZ = "29"; } else { strZ = "28"; } } strY = y >= 10 ? String.valueOf(y) : ("0" + y); return x + "-" + strY + "-" + strZ; } /** * 功能:得到当前月份下个年的月底 格式为:xxxx-yy-zz (eg: 2007-12-31)<br> * * @return String * @author pure */ public String thisNextYearMonthEnd() { String strY = null; String strZ = null; boolean leap = false; x = localTime.get(Calendar.YEAR) + 1; y = localTime.get(Calendar.MONTH) + 1; if (y == 1 || y == 3 || y == 5 || y == 7 || y == 8 || y == 10 || y == 12) { strZ = "31"; } if (y == 4 || y == 6 || y == 9 || y == 11) { strZ = "30"; } if (y == 2) { leap = leapYear(x); if (leap) { strZ = "29"; } else { strZ = "28"; } } strY = y >= 10 ? String.valueOf(y) : ("0" + y); return x + "-" + strY + "-" + strZ; } /** * 功能:得到当前月份下个年的月底 格式为:xxxx-yy-zz (eg: 2007-12-31)<br> * * @return String * @author pure */ public String thisNextYearMonthEnd(String s) { Calendar rr = getCalendarByStr(s); String strY = null; String strZ = null; boolean leap = false; x = rr.get(rr.YEAR) + 1; y = rr.get(rr.MONTH) + 1; if (y == 1 || y == 3 || y == 5 || y == 7 || y == 8 || y == 10 || y == 12) { strZ = "31"; } if (y == 4 || y == 6 || y == 9 || y == 11) { strZ = "30"; } if (y == 2) { leap = leapYear(x); if (leap) { strZ = "29"; } else { strZ = "28"; } } strY = y >= 10 ? String.valueOf(y) : ("0" + y); return x + "-" + strY + "-" + strZ; } /** * 功能:得到当前季度季初 格式为:xxxx-yy-zz (eg: 2007-10-01)<br> * * @return String * @author pure */ public String thisSeason() { String dateString = ""; x = localTime.get(Calendar.YEAR); y = localTime.get(Calendar.MONTH) + 1; if (y >= 1 && y <= 3) { dateString = x + "-" + "01" + "-" + "01"; } if (y >= 4 && y <= 6) { dateString = x + "-" + "04" + "-" + "01"; } if (y >= 7 && y <= 9) { dateString = x + "-" + "07" + "-" + "01"; } if (y >= 10 && y <= 12) { dateString = x + "-" + "10" + "-" + "01"; } return dateString; } /** * 功能:得到当前季度季末 格式为:xxxx-yy-zz (eg: 2007-12-31)<br> * * @return String * @author pure */ public String thisSeasonEnd() { String dateString = ""; x = localTime.get(Calendar.YEAR); y = localTime.get(Calendar.MONTH) + 1; if (y >= 1 && y <= 3) { dateString = x + "-" + "03" + "-" + "31"; } if (y >= 4 && y <= 6) { dateString = x + "-" + "06" + "-" + "30"; } if (y >= 7 && y <= 9) { dateString = x + "-" + "09" + "-" + "30"; } if (y >= 10 && y <= 12) { dateString = x + "-" + "12" + "-" + "31"; } return dateString; } /** * 功能:得到当前季度季末 格式为:xxxx-yy-zz (eg: 2007-12-31)<br> * * @return String * @author pure */ public String thisSeasonEnd(String s) { Calendar rr = getCalendarByStr(s); String dateString = ""; x = rr.get(rr.YEAR); y = rr.get(rr.MONTH) + 1; if (y >= 1 && y <= 3) { dateString = x + "-" + "03" + "-" + "31"; } if (y >= 4 && y <= 6) { dateString = x + "-" + "06" + "-" + "30"; } if (y >= 7 && y <= 9) { dateString = x + "-" + "09" + "-" + "30"; } if (y >= 10 && y <= 12) { dateString = x + "-" + "12" + "-" + "31"; } return dateString; } /** * 功能:得到当前年份年初 格式为:xxxx-yy-zz (eg: 2007-01-01)<br> * * @return String * @author pure */ public String thisYear() { x = localTime.get(Calendar.YEAR); return x + "-01" + "-01"; } public String thisYear(String s) { Calendar rr = getCalendarByStr(s); x = rr.get(rr.YEAR); return x + "-01" + "-01"; } public String nextYear() { x = localTime.get(Calendar.YEAR) + 1; return x + "-01" + "-01"; } public String nextYear(String s) { Calendar rr = getCalendarByStr(s); x = rr.get(rr.YEAR) + 1; return x + "-01" + "-01"; } /** * 功能:得到当前年份年底 格式为:xxxx-yy-zz (eg: 2007-12-31)<br> * * @return String * @author pure */ public String thisYearEnd(String s) { Calendar rr = getCalendarByStr(s); x = localTime.get(rr.YEAR); return x + "-12" + "-31"; } /** * 功能:得到当前年份年底 格式为:xxxx-yy-zz (eg: 2007-12-31)<br> * * @return String * @author pure */ public String thisYearEnd() { x = localTime.get(Calendar.YEAR); return x + "-12" + "-31"; } /** * 功能:判断输入年份是否为闰年<br> * * @param year * @return 是:true 否:false * @author pure */ public boolean leapYear(int year) { boolean leap; if (year % 4 == 0) { if (year % 100 == 0) { if (year % 400 == 0) leap = true; else leap = false; } else leap = true; } else leap = false; return leap; } /** * 判断一天是否是周末 * * @param d * @return */ public boolean checkWeekendDay(Date d) { Calendar cal = Calendar.getInstance(); cal.setTime(d); if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { return true; } return false; } }
timeUtil
package com..common.util; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; /** * 时间工具类 */ public class TimeUtils { private TimeUtils() { } private static final String YYYY = "yyyy-MM-dd"; private static final String YYYYHH = "yyyy-MM-dd HH:mm:ss"; /** * 取得yyyy-MM-dd HH:mm:ss格式的时间 * * @return */ public static String yyyyMMddHHmmss(Date date) { return dateFormat4yyyyMMddHHmmss().format(date); } public static Date yyyyMMdd(String formatdate) { try { return dateFormat4yyyyMMdd().parse(formatdate); } catch (Exception e) { throw new IllegalStateException(formatdate, e); } } public static String yyyyMMdd(Date date) { return dateFormat4yyyyMMdd().format(date); } public static String format(DateFormat format, Date date) { try { return format.format(date); } catch (Exception e) { throw new IllegalArgumentException(date.toString(), e); } } /** * @return */ public static SimpleDateFormat dateFormat4yyyyMMddHHmmss() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } /** * @return yyyy-MM-dd格式 */ public static SimpleDateFormat dateFormat4yyyyMMdd() { return new SimpleDateFormat("yyyy-MM-dd"); } /** * 将字符串格式yyyyMMdd的字符串转为日期,格式"yyyy-MM-dd" * * @param date 日期字符串 * @return 返回格式化的日期 * @throws ParseException 分析时意外地出现了错误异常 */ public static String strToDateFormat(String date) { try { if (StringUtils.isEmpty(date)) { return date; } SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd"); formatter.setLenient(false); Date newDate = formatter.parse(date); formatter = new SimpleDateFormat("yyyy-MM-dd"); return formatter.format(newDate); } catch (ParseException e) { throw new IllegalStateException(date, e); } } /** * 当前季度的开始时间,即2012-01-1 00:00:00 * * @return */ public static Date getCurrentQuarterStartTime(Date nowDate) throws Exception { SimpleDateFormat longSdf = new SimpleDateFormat(YYYYHH); SimpleDateFormat shortSdf = new SimpleDateFormat(YYYY); Calendar c = Calendar.getInstance(); c.setTime(nowDate); int currentMonth = c.get(Calendar.MONTH) + 1; Date now = null; if (currentMonth >= 1 && currentMonth <= 3) c.set(Calendar.MONTH, 0); else if (currentMonth >= 4 && currentMonth <= 6) c.set(Calendar.MONTH, 3); else if (currentMonth >= 7 && currentMonth <= 9) c.set(Calendar.MONTH, 6); else if (currentMonth >= 10 && currentMonth <= 12) c.set(Calendar.MONTH, 9); c.set(Calendar.DATE, 1); now = longSdf.parse(shortSdf.format(c.getTime()) + " 00:00:00"); return now; } /** * 当前半年的开始时间,即2012-01-01 00:00:00,2012-06-01 00:00:00 * * @return */ public static Date getCurrentYearStartTime(Date nowDate) throws Exception { SimpleDateFormat longSdf = new SimpleDateFormat(YYYYHH); SimpleDateFormat shortSdf = new SimpleDateFormat(YYYY); Calendar c = Calendar.getInstance(); c.setTime(nowDate); int currentMonth = c.get(Calendar.MONTH) + 1; if (currentMonth >= 1 && currentMonth <= 6) c.set(Calendar.MONTH, 0); else if (currentMonth >= 7 && currentMonth <= 12) c.set(Calendar.MONTH, 6); c.set(Calendar.DATE, 1); Date now = longSdf.parse(shortSdf.format(c.getTime()) + " 00:00:00"); return now; } /** * 当前半年的结束时间,即2012-06-30 23:59:59,2012-12-31 23:59:59 * * @return */ public static Date getCurrentYearEndTime(Date nowDate) throws Exception { SimpleDateFormat longSdf = new SimpleDateFormat(YYYYHH); SimpleDateFormat shortSdf = new SimpleDateFormat(YYYY); Calendar c = Calendar.getInstance(); c.setTime(nowDate); int currentMonth = c.get(Calendar.MONTH) + 1; if (currentMonth >= 1 && currentMonth <= 6) { c.set(Calendar.MONTH, 5); c.set(Calendar.DATE, 30); } else if (currentMonth >= 7 && currentMonth <= 12) { c.set(Calendar.MONTH, 11); c.set(Calendar.DATE, 31); } Date now = longSdf.parse(shortSdf.format(c.getTime()) + " 23:59:59"); return now; } /** * 当月第一天,即2012-03-31 23:59:59 * * @return */ public static Date getCurrentMonthMiddleday(Date nowDate) { // 获取当月第一天和最后一天 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); // 获取前月的第一天 Calendar cale = Calendar.getInstance(); cale.setTime(nowDate); cale.add(Calendar.MONTH, 0); cale.set(Calendar.DAY_OF_MONTH, 15); String firstday = format.format(cale.getTime()); System.out.println("firstday = " + firstday); return cale.getTime(); } /** * 当前季度的结束时间,即2012-03-31 23:59:59 * * @return */ public static Date getCurrentQuarterEndTime(Date nowDate) throws Exception { SimpleDateFormat longSdf = new SimpleDateFormat(YYYYHH); SimpleDateFormat shortSdf = new SimpleDateFormat(YYYY); Calendar c = Calendar.getInstance(); c.setTime(nowDate); int currentMonth = c.get(Calendar.MONTH) + 1; Date now = null; if (currentMonth >= 1 && currentMonth <= 3) { c.set(Calendar.MONTH, 2); c.set(Calendar.DATE, 31); } else if (currentMonth >= 4 && currentMonth <= 6) { c.set(Calendar.MONTH, 5); c.set(Calendar.DATE, 30); } else if (currentMonth >= 7 && currentMonth <= 9) { c.set(Calendar.MONTH, 8); c.set(Calendar.DATE, 30); } else if (currentMonth >= 10 && currentMonth <= 12) { c.set(Calendar.MONTH, 11); c.set(Calendar.DATE, 31); } now = longSdf.parse(shortSdf.format(c.getTime()) + " 23:59:59"); return now; } /** * 当年中间的一天,即2019-06-30 * * @return */ public static Date getMiddleDayOfYear(Date nowDate) { // 获取前月的第一天 Calendar cale = Calendar.getInstance(); cale.setTime(nowDate); cale.set(Calendar.MONTH, 5); cale.set(Calendar.DAY_OF_MONTH, 30); return cale.getTime(); } /** * 当年尾的一天,即2019-12-31 * * @return */ public static Date getEndDayOfYear(Date nowDate) { // 获取前月的第一天 Calendar cale = Calendar.getInstance(); cale.setTime(nowDate); cale.set(Calendar.MONTH, 11); cale.set(Calendar.DAY_OF_MONTH, 31); return cale.getTime(); } /** * 获取制定年月的 日历工作天数 * * @param year * @param month * @return */ public static List<String> getDates(int year, int month) { List<String> dates = new ArrayList<>(); Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, month - 1); cal.set(Calendar.DATE, 1); while (cal.get(Calendar.YEAR) == year && cal.get(Calendar.MONTH) < month) { int day = cal.get(Calendar.DAY_OF_WEEK); if (!(day == Calendar.SUNDAY || day == Calendar.SATURDAY)) { dates.add(TimeUtils.yyyyMMdd((Date) cal.getTime().clone())); } cal.add(Calendar.DATE, 1); } return dates; } /** * 获取制定年月获取一年的周末 * * @param year * @return */ public static List<String> getDatesWeekend(int year) { List<String> dates = new ArrayList<>(); Calendar c = Calendar.getInstance(); c.set(year, 0, 1); Calendar c2 = Calendar.getInstance(); c2.set(year + 1, 0, 1); while (c.compareTo(c2) < 0) { if (c.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || c.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { dates.add(TimeUtils.yyyyMMdd((Date) c.getTime().clone())); } // 日期+1 c.add(Calendar.DATE, 1); } return dates; } }
以上是关于简单算法3的主要内容,如果未能解决你的问题,请参考以下文章