1. 在不使用 StringBuffer 的前提下,怎麼反轉一個字符串?解決方案html
思路:將字符串轉成字符數組,倒敘遍歷,而後拼接成字符串。java
public class StringReverseExample { public static void main(String args[]) { //quick wasy to reverse String in Java - Use StringBuffer String word = "HelloWorld"; String reverse = new StringBuffer(word).reverse().toString(); System.out.printf(" original String : %s , reversed String %s %n", word, reverse); //another quick to reverse String in Java - use StringBuilder word = "WakeUp"; reverse = new StringBuilder(word).reverse().toString(); System.out.printf(" original String : %s , reversed String %s %n", word, reverse); //one way to reverse String without using StringBuffer or StringBuilder is writing //own utility method word = "Band"; reverse = reverse(word); System.out.printf(" original String : %s , reversed String %s %n", word, reverse); } public static String reverse(String source) { if (source == null || source.isEmpty()) { return source; } String reverse = ""; for (int i = source.length() - 1; i >= 0; i--) { reverse = reverse + source.charAt(i); } return reverse; } }
2. Java 中,怎麼獲取一個文件中單詞出現的最高頻率?解決方案git
思路:將文本中的字符分詞,而後使用 HashMap 的存儲,key 存儲單詞,value 存儲出現次數。正則表達式
public class Problem { public static void main(String args[]) { Map<String, Integer> wordMap = buildWordMap("C:/temp/words.txt"); List<Map.Entry<String, Integer>> list = sortByValueInDecreasingOrder(wordMap); System.out.println("List of repeated word from file and their count"); for (Map.Entry<String, Integer> entry : list) { if (entry.getValue() > 1) { System.out.println(entry.getKey() + " => " + entry.getValue()); } } } public static Map<String, Integer> buildWordMap(String fileName) { // Using diamond operator for clean code Map<String, Integer> wordMap = new HashMap<>(); // Using try-with-resource statement for automatic resource management try (FileInputStream fis = new FileInputStream(fileName); DataInputStream dis = new DataInputStream(fis); BufferedReader br = new BufferedReader(new InputStreamReader(dis))) { // words are separated by whitespace Pattern pattern = Pattern.compile("\\s+"); String line = null; while ((line = br.readLine()) != null) { // do this if case sensitivity is not required i.e. Java = java line = line.toLowerCase(); String[] words = pattern.split(line); for (String word : words) { if (wordMap.containsKey(word)) { wordMap.put(word, (wordMap.get(word) + 1)); } else { wordMap.put(word, 1); } } } } catch (IOException ioex) { ioex.printStackTrace(); } return wordMap; } public static List<Map.Entry<String, Integer>> sortByValueInDecreasingOrder(Map<String, Integer> wordMap) { Set<Map.Entry<String, Integer>> entries = wordMap.entrySet(); List<Map.Entry<String, Integer>> list = new ArrayList<>(entries); list.sort((o1, o2) -> (o2.getValue()).compareTo(o1.getValue())); return list; } }
3. 在沒有使用臨時變量的狀況如何交換兩個整數變量的值?數組
思路:本身構造第三方變量。緩存
int a = 5, b = 8; // 方法一:加減法 a = a + b; // 本身造一個臨時變量 b = a - b; a = a - b; // 方法二:異或法 a = a ^ b; // 0101 ^ 1000 = 1100 b = b ^ a; // 1000 ^ (0101 ^ 1000) = 1000 ^ 1000 ^ 0101 = 0000 ^ 0101 = 0101 a = a ^ b; // (0101 ^ 1000) ^ 0101 = 0101 ^ 0101 ^ 1000 = 0000 ^ 1000 = 1000
4. Java 中如何將字符串轉換爲整數?app
思路:①首先校驗字符串;②判斷數字開頭是正號仍是負號,設置一個標誌位,正號爲 1,負號爲 -1;③判斷字符是否在 0 到 9 以內,是轉數字,不然跳出。ide
public static int stringToInt(String str) { int index = 0; int sign = 1; int digit = 0; int total = 0; char ch; // 1.1判斷字符串是否爲空。 if (str.length() == 0) { return 0; } // 1.2判斷字符串中是否含有空格,若是有就跳過。 while (str.charAt(index) == ' ' && index < str.length()) { index++; } // 2.判斷字符串爲正仍是負。 if (str.charAt(index) == '+' || str.charAt(index) == '-') { if (str.charAt(index) == '+') sign = 1; else { sign = -1; } index++; } // 3.進行處理。 while (index < str.length()) { ch = str.charAt(index); if (ch < '0' || ch > '9') break; digit = ch - '0'; //校驗後續 total = total * 10 + digit; 操做以後數字的絕對值的大小,若是超出 MAX_VALUE,則根據負號標誌位進行相應的賦值。 if (Integer.MAX_VALUE / 10 < total || Integer.MAX_VALUE / 10 == total && Integer.MAX_VALUE % 10 < digit) return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; total = total * 10 + digit; index++; } return sign * total; }
5. 給定一個 txt 文件,如何獲得某字符串出現的次數。ui
思路:使用正則表達式。this
public static int count() throws IOException { //讀入文本(字符),用FileReader->BufferedReader //讀入輸入(字節),用FileInputStream->InputStreamReader->BufferedReader String path = Test.class.getResource("/1.txt").getPath(); BufferedReader br = new BufferedReader(new FileReader(path)); StringBuilder sb = new StringBuilder(); while (true) { String str = br.readLine(); if (str == null) { break; } sb.append(str); } Pattern p = Pattern.compile("mobnet"); Matcher m = p.matcher(sb); int count = 0; while (m.find()) { count++; } return count; }
6. Java 中如何利用泛型寫一個 LRU/FIFO 緩存?參考資料
思路:使用 LinkedHashMap 的特性,在參考資料中還有使用 HashMap 的方法去實現,具體思路見參考資料。
7. 打印出數組中的重複元素。參考資料
思路1:雙重循環遍歷,第一層循環取數,第二層循環負責將其餘元素與第一層取出的元素進行比較是否相等。時間複雜度 O(n²)。
思路2:藉助 Set 集合的特性,set.add(item) == false,添加失敗說明 set 集合中已經存在該元素,只須要將統計數量加 1 便可,添加成功說明 set 集合中不存在該元素,將統計數量置爲 1。
思路3:藉助 HashMap 集合的特性,使用 key 保存數組元素,value 用於統計數量。