Archive for November 23rd, 2013
- In: leetcode
- 5 Comments
遇见这种matrix题就腿发软,bf给讲了个四条边bound的方法,立刻15分钟bug free了。高兴够呛。
public int[][] generateMatrix(int n) { int[][] res = new int[n][n]; int k = 1; int top = 0, bottom = n - 1, left = 0, right = n - 1; while (left < right && top < bottom) { for (int j = left; j < right; j++) { res[top][j] = k++; } for (int i = top; i < bottom; i++) { res[i][right] = k++; } for (int j = right; j > left; j--) { res[bottom][j] = k++; } for (int i = bottom; i > top; i--) { res[i][left] = k++; } left++; right--; top++; bottom--; } if (n % 2 != 0) res[n / 2][n / 2] = k; return res; }
Tags: matrix
[leetcode] Valid Number
Posted November 23, 2013
on:- In: leetcode
- 7 Comments
这就是典型的try and fail,尼玛谁知道什么算是数什么不算啊?让我用眼睛看我也不知道啊!总之,试出来的规则是这样的:
- AeB代表A * 10 ^ B
- A可以是小数也可以是整数,可以带正负号
- .35, 00.神马的都算valid小数;就”.”单独一个不算
- B必须是整数,可以带正负号
- 有e的话,A,B就必须同时存在
算法就是按e把字符串split了,前面按A的法则做,后面按B做。
public boolean isNumber(String s) { s = s.trim(); if (s.length() > 0 && s.charAt(s.length() - 1) == 'e') return false; //avoid "3e" which is false String[] t = s.split("e"); if (t.length == 0 || t.length > 2) return false; boolean res = valid(t[0], false); if (t.length > 1) res = res && valid(t[1], true); return res; } private boolean valid(String s, boolean hasDot) { if (s.length() > 0 && (s.charAt(0) == '+' || s.charAt(0) == '-')) //avoid "1+", "+", "+." s = s.substring(1); char[] arr = s.toCharArray(); if (arr.length == 0 || s.equals(".")) return false; for (int i = 0; i < arr.length; i++) { if (arr[i] == '.') { if (hasDot) return false; hasDot = true; } else if (!('0' <= arr[i] && arr[i] <= '9')) { return false; } } return true; }
Tags: math