一些簡單的演算法題
阿新 • • 發佈:2018-12-10
1.將兩個有序連結串列合併為一個新的有序連結串列並返回,新連結串列是通過拼接給定的兩個連結串列的所有節點組成的
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode l1Current = l1;
ListNode l2Current = l2;
if (null == l1Current) return l2Current;
if (null == l2Current) return l1Current;
ListNode head = null ;
if (l1Current.val < l2Current.val) {
head = l1Current;
l1Current = l1Current.next;
} else {
head = l2Current;
l2Current = l2Current.next;
}
ListNode current = head;
while (null != l1Current && null != l2Current) {
if (l1Current.val < l2Current.val) {
current.next = l1Current;
l1Current = l1Current.next;
} else {
current.next = l2Current;
l2Current = l2Current.next;
}
current = current.next;
}
if (null == l1Current) current.next = l2Current;
if (null == l2Current) current.next = l1Current;
return head;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
2.給定一個包括”(“,”)”,”{“,”}”,”[“,”]”的字串,來判斷字串是否有效,即括號匹配
(利用棧實現)
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class Solution {
private static final Map<String, String> MAP = new HashMap<String, String>();
static {
Solution.MAP.put(")", "(");
Solution.MAP.put("}", "{");
Solution.MAP.put("]", "[");
}
public boolean isValid(String s) {
if (null == s)
throw new NullPointerException("s is null");
if ("".equals(s)) return true;
Stack<String> stack = new Stack<String>();
for (int i = 0; i < s.length(); i++) {
String now = s.substring(i, i + 1);
if (!Solution.MAP.containsKey(now))
stack.push(now);
else {
if (stack.size() == 0) return false;
String last = stack.pop();
if (!Solution.MAP.get(now).equals(last)) return false;
}
}
return stack.size() == 0;
}
}
3,字串在檔案中出現的次數
import java.io.BufferedReader;
import java.io.FileReader;
public class Test {
public static int countWordInFile(String filename, String word) {
int count = 0;
try (FileReader fr = new FileReader(filename)) {
try (BufferedReader br = new BufferedReader(fr)) {
String line = null;
while ((line = br.readLine()) != null) {
int index = -1;
while (line.length() >= word.length() && (index = line.indexOf(word)) >= 0) {
count++;
line = line.substring(index + word.length());
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return count;
}
public static void main(String[] args) {
System.out.println(countWordInFile("e:\\blog\\test\\temp.txt", "public"));
}
}