第一次算法面试回顾
前几天学习的时候就被触发记忆了,想起了上学期期末自己投简面试的接到的第一家面试,现在想起来那会自己确实算法思维很差,就连应试的都没咋准备,今天了,还是准备的很少很少。
上次学习中学到一个文件夹下查询不同类型文件的算法,用的是IO和HashMap,这里增加了难度,从一个父目录下去查找,里面有很多子文件夹,子文件的层级不一,最后查询指定文件类型的路径(或者说依旧是不同类型文件的个数),这里采用在原来的基础上增加递归思想即可完成,但要注意递归的隐患。下面用java具体实现一下该算法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| package digui;
import java.io.File;
public class Demo2 { public static void main(String[] args) {
String strFile = "/users/ethan.liu/desktop/"; File file = new File(strFile);
String[] types = {"ppt", "java", "py", "docx", "zip"}; getSearchFile(file, types); }
private static void getSearchFile(File file, String[] types) { if (!file.exists()) { throw new RuntimeException("输入文件路径不存在"); } else { File[] files = file.listFiles(); for (File f : files) { if (f.isFile()) { for (String type : types) { if (f.getName().endsWith("." + type)) { System.out.println(f.getAbsoluteFile()); } } } else if (f.isDirectory()) { getSearchFile(f, types); } } } } }
|