ARTS是什么? Algorithm:每周至少做一个LeetCode的算法题 Review:阅读并点评至少一篇英文文章 Tip:学习至少一个技术技巧 Share:分享一篇有观点和思考的技术文章
Algorithm
package leetcode;/*** @className: LeetCode03* @description:* 编写一个函数来查找字符串数组中的最长公共前缀。* 如果不存在公共前缀,返回空字符串 ""。** 示例 1:* 输入:strs = ["flower","flow","flight"]* 输出:"fl"** 示例 2:* 输入:strs = ["dog","racecar","car"]* 输出:""* 解释:输入不存在公共前缀。* @author: Miluo* @date: 2021/3/8**/public class LeetCode03 {public String longestCommonPrefix(String[] strs) {int min = 9999;char c = '0';String prefix = "";if (strs.length == 0){return prefix;}//计算数组内 位数最少是多少for (int i = 0; i < strs.length; i++) {if (strs[i].length() == 0){return prefix;}if (strs[i].length() < min){min = strs[i].length();}}//根据最小位数min,遍历数组前min位for (int j = 0; j < min; j++) {for (int i = 0; i < strs.length; i++) {if (i == 0){c = strs[i].charAt(j);}else {if (strs[i].charAt(j) != c){return prefix;}}}prefix = prefix.concat(String.valueOf(c));}return prefix;}//参考题解//依次遍历字符串数组中的每个字符串,对于每个遍历到的字符串,更新最长公共前缀,//当遍历完所有的字符串以后,即可得到字符串数组中的最长公共前缀。public String longestCommonPrefix(String[] strs) {if (strs == null || strs.length == 0) {return "";}String prefix = strs[0];int count = strs.length;for (int i = 1; i < count; i++) {prefix = longestCommonPrefix(prefix, strs[i]);if (prefix.length() == 0) {break;}}return prefix;}public String longestCommonPrefix(String str1, String str2) {int length = Math.min(str1.length(), str2.length());int index = 0;while (index < length && str1.charAt(index) == str2.charAt(index)) {index++;}return str1.substring(0, index);}}
Review
20 controversial programming opinions
Tip
可使用 try-with-resources 语句安全地释放资源
- 这里所谓的资源(resource)是指在程序完成后,必须关闭的对象, try-with-resources 语句确保了每个资源在语句结束时关闭;
- 使用 Java 7 新增的 try-with-resources 语句 代替 try-finally 语句进行资源关闭,不仅代码更精简而且更安全;
- 支持 try-with-resources 语句 的类必须都实现
AutoCloseable接口,同样的,我们自定义的类也可以实现这个接口来帮助我们进行一些安全的自动化释放资源; - Java 9 对 try-with-resources 语句进行了改进,如果你有一个资源是 final 或等效于 final 变量, 则可以在 try-with-resources 语句中使用该变量,无需在 try-with-resources 语句中再声明一个新的变量。
public static void demo() {File file = new File("try-with-resources-demo.txt");try (FileWriter fileWriter = new FileWriter(file);BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);FileReader fileReader = new FileReader(file);BufferedReader bufferedReader = new BufferedReader(fileReader);) {bufferedWriter.write("now is:" + LocalDateTime.now() + "\n\r");bufferedWriter.write("availableProcessors are : " + Runtime.getRuntime().availableProcessors() + "\n\r");bufferedWriter.write("totalMemory is : " + Runtime.getRuntime().totalMemory() + "\n\r");bufferedWriter.write("maxMemory is : " + Runtime.getRuntime().maxMemory() + "\n\r");bufferedWriter.write("freeMemory is : " + Runtime.getRuntime().freeMemory() + "\n\r");bufferedWriter.flush();StringBuffer readResult = new StringBuffer("");String oneLine = null;while (null != (oneLine = bufferedReader.readLine())) {readResult.append(oneLine + "\n\r");}System.out.println(readResult.toString());} catch (IOException ioe) {ioe.printStackTrace();}}
