1. Largest Number 这一题技巧性很强,对数组排序根据a+b和b+a进行比较。
public class Solution {
public String largestNumber(int[] nums) {
String[] strs = new String[nums.length];
for(int i = 0; i < nums.length; i++){
strs[i] = String.valueOf(nums[i]);
}
Arrays.sort(strs, new Comparator<String>(){
public int compare(String s1, String s2){
String leftRight = s1 + s2;
String rightLeft = s2 + s1;
return rightLeft.compareTo(leftRight);
}
});
StringBuilder sb = new StringBuilder();
for(String s : strs){
sb.append(s);
}
while(sb.charAt(0) == '0' && sb.length() > 1){
sb.deleteCharAt(0);
}
return sb.toString();
}
}
2. Minimum Window Substring 使用2个map座位window
public class Solution {
public String minWindow(String s, String t) {
if(t.length()>s.length())
return "";
String result = "";
//character counter for t
HashMap<Character, Integer> target = new HashMap<Character, Integer>();
for(int i = 0; i < t.length(); i++){
char c = t.charAt(i);
if (target.containsKey(c)) {
target.put(c, target.get(c) + 1);
} else {
target.put(c, 1);
}
}
// character counter for s
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int left = 0;
int minLen = s.length() + 1;
int count = 0; // the total of mapped characters
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if(target.containsKey(c)){
if(map.containsKey(c)){
if(map.get(c) < target.get(c)){
count++;
}
map.put(c,map.get(c)+1);
}else{
map.put(c,1);
count++;
}
}
if(count == t.length()){
char sc = s.charAt(left);
while (!map.containsKey(sc) || map.get(sc) > target.get(sc)) {
if (map.containsKey(sc) && map.get(sc) > target.get(sc))
map.put(sc, map.get(sc) - 1);
left++;
sc = s.charAt(left);
}
if (i - left + 1 < minLen) {
result = s.substring(left, i + 1);
minLen = i - left + 1;
}
}
}
return result;
}
}
3. Reverse Linked List 下面是两种不同的添加反转方法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if (head == null) {
return null;
}
/*
ListNode start = new ListNode(0);
start.next = head;
ListNode p = head;
ListNode q = p.next;
while (p.next != null) {
q = p.next.next;
p.next.next = start.next;
start.next = p.next;
p.next = q;
}
return start.next;
*/
/* for example : 432156
* head:4, p:1, q:5, r:6
*/
ListNode p = head, q, r;
while (p.next != null) {
q = p.next;
r = q.next;
q.next = head;
p.next = r;
head = q;
}
return head;
}
}