面試算法題

    /**
     * 編寫一個截取字符串的函數,輸入為一個字符串和字節數,輸出為按字節截取的字符串。
     * 但是要保證漢字不被截半個,如輸入(“我ABC”,4),應該輸出“我AB”;
     * 輸入(“我ABC漢DEF”,6),應該輸出“我ABC”而不是“我ABC”+“漢”的半個
     *
     * 考點:漢字截半時對應字節的ASCII碼小于0
     */

    public static void main(String[] args) throws Exception {
        String src = "我ABC漢DEF";
        System.out.println(spiltString(src, 4));
        System.out.println(spiltString(src, 6));
    }

    private static String spiltString(String src, int len) throws Exception {
        if (src == null || src.equals("")) {
            System.out.println("The source String is null!");
            return null;
        }
        byte[] srcBytes = src.getBytes("GBK");
        if (len > srcBytes.length) {
            len = srcBytes.length;
        }
        if (srcBytes[len] < 0) {
            return new String(srcBytes, 0, --len);
        } else {
            return new String(srcBytes, 0, len);
        }
    }
  /**
     * 在實際開發工作中,對字符串的處理是最常見的編程任務。
     * 本題目即是要求程序對用戶輸入的字符串進行處理。具體規則如下:
     * a)把每個單詞的首字母變為大寫
     * b)把數字與字母之間用下劃線字符(_)分開,使得更清晰
     * c)把單詞中間有多個空格的調整為1個空格
     * 例如:
     * 用戶輸入:
     * you and me what      cpp2005program
     * 則程序輸出:
     * You And Me What Cpp_2005_program
     * 
     * 相關文章:http://blog.csdn.net/u013091087/article/details/43793149
     */

    public static void main(String[] args) {
        System.out.println("please input:");
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        scanner.close();
        String[] ss = s.split("\\\\s+"); // \\s表示空格、\\t、\\n等空白字符
        for (int i = 0; i < ss.length; i++) {
            String up = (ss[i].charAt(0) + "").toUpperCase(); // 大寫
            StringBuffer sb = new StringBuffer(ss[i]);
            ss[i] = sb.replace(0, 1, up).toString(); // 首字母替換為大寫
            Matcher m = Pattern.compile("\\\\d+").matcher(ss[i]);
            int fromIndex = 0;
            while (m.find()) {
                String num = m.group();
                int index = ss[i].indexOf(num, fromIndex);
                StringBuffer sbNum = new StringBuffer(ss[i]);
                ss[i] = sbNum.replace(index, index + num.length(),
                        "_" + num + "_").toString();
                fromIndex = index + num.length() + 2;
                if (ss[i].startsWith("_")) { // 去頭"_"
                    ss[i] = ss[i].substring(1);
                }
                if (ss[i].endsWith("_")) { // 去尾"_"
                    ss[i] = ss[i].substring(0, ss[i].length() - 1);
                }
            }
        }
        for (int i = 0; i < ss.length - 1; i++) {
            System.out.print(ss[i] + " ");
        }
        System.out.print(ss[ss.length - 1]);
    }
    /**
     * 兩個有序數組的合并函數
     * @param a
     * @param b
     * @return
     */
    public static int[] MergeList(int a[], int b[]) {
        int result[];
        result = new int[a.length + b.length];
        //i:用于標示a數組    j:用來標示b數組  k:用來標示傳入的數組
        int i = 0, j = 0, k = 0;

        while (i < a.length && j < b.length) {
            if (a[i] <= b[j]) {
                result[k++] = a[i++];
            } else {
                result[k++] = b[j++];
            }
        }
            /* 后面連個while循環是用來保證兩個數組比較完之后剩下的一個數組里的元素能順利傳入 */
        while (i < a.length)
            result[k++] = a[i++];
        while (j < b.length)
            result[k++] = b[j++];

        return result;
    }
    public static int rank(int key, int a[]) {
        return rank(key, a, 0, a.length - 1);
    }

    public static int rank(int key, int a[], int lo, int hi) {
        if (lo > hi)
            return -1;//error
        int mid = lo + (hi - lo) / 2;
        if (key < a[mid])
            return rank(key, a, lo, mid - 1);
        else if (key > a[mid])
            return rank(key, a, mid + 1, hi);
        else
            return mid;
    }

/**
 * 將數組中奇數放到偶數前面java實現
 * 例如:給定 int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9};
 *      輸出 int[] nums = {1, 9, 3, 7, 5, 6, 4, 8, 2};
 */
public class TokenCode1 {
    public static void main(String[] args) {
        // write your code here
        int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        int[] result = convertNums(nums);
        System.out.println(Arrays.toString(result));
    }

    private static int[] convertNums(int[] nums) {
        int i = 0;
        int j = nums.length - 1;
        while (i < j) {
            while (i < j && nums[i] % 2 != 0) {
                i++;
            }
            while (i < j && nums[j] % 2 == 0) {
                j--;
            }
            swap(nums, i, j);
        }
        return nums;
    }

    private static void swap(int[] nums, int a, int b) {
        int temp = nums[a];
        nums[a] = nums[b];
        nums[b] = temp;
    }
}
/**
 * 鏈表反轉
 */
public class TokenCode2 {
    public static void main(String[] args) {
        Node headNode = buildTestNode();
        printNodes(headNode);
        printNodes(convertNodes(headNode));
    }

    /**
     * 鏈表反轉
     * @param node
     * @return
     */
    private static Node convertNodes(Node node) {
        Node pre = null;
        Node now = node;
        while (now != null) {
            Node next = now.child;
            now.child = pre;
            pre = now;
            now = next;
        }
        return pre;
    }


    /**
     * 生成測試頭節點
     * @return
     */
    private static Node buildTestNode() {
        Node node5 = new Node("5", null);
        Node node4 = new Node("4", node5);
        Node node3 = new Node("3", node4);
        Node node2 = new Node("2", node3);
        Node head = new Node("1", node2);
        return head;
    }

    /**
     * 打印列表
     * @param node
     */
    private static void printNodes(Node node) {
        System.out.print(node.value);
        if (node.child != null) {
            System.out.print(" -> ");
            printNodes(node.child);
        } else {
            System.out.println();
        }
    }
}
/**
 * 合并兩個有序鏈表
 * 例如
 * headA = 1 -> 3 -> 5 -> 7 -> 9
 * headB = 2 -> 4 -> 6 -> 8 -> 10
 * result = 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10
 */
public class TokenCode3 {
    public static void main(String[] args) {
        Node headA = buildTestNode_A();
        printNodes(headA);
        Node headB = buildTestNode_B();
        printNodes(headB);
        printNodes(mergeNodes(headA, headB));
    }

    /**
     * 合并數組
     * @param headA
     * @param headB
     * @return
     */
    private static Node mergeNodes(Node headA, Node headB) {

        if (headA == null) {
            return headB;
        }
        if (headB == null) {
            return headA;
        }

        Node result;
        if (headA.value <= headB.value) {
            result = headA;
            result.next = mergeNodes(headA.next, headB);
        } else {
            result = headB;
            result.next = mergeNodes(headA, headB.next);
        }
        return result;
    }

    /**
     * 生成測試頭節點
     *
     * @return
     */
    private static Node buildTestNode_A() {
        Node node5 = new Node(9, null);
        Node node4 = new Node(7, node5);
        Node node3 = new Node(5, node4);
        Node node2 = new Node(3, node3);
        Node head = new Node(1, node2);
        return head;
    }

    /**
     * 生成測試頭節點
     *
     * @return
     */
    private static Node buildTestNode_B() {
        Node node5 = new Node(10, null);
        Node node4 = new Node(8, node5);
        Node node3 = new Node(6, node4);
        Node node2 = new Node(4, node3);
        Node head = new Node(2, node2);
        return head;
    }

    /**
     * 打印列表
     *
     * @param node
     */
    private static void printNodes(Node node) {
        System.out.print(node.value);
        if (node.next != null) {
            System.out.print(" -> ");
            printNodes(node.next);
        } else {
            System.out.println();
        }
    }
}
/**
 * 樹的最大深度
 */
public class TokenCode4 {
    public static void main(String[] args) {
        TreeNode head = buildTestTree();
        printTree(head);
        System.out.println();
        System.out.print("count = " + getCount(head));
    }

    /**
     * 樹的最大深度
     * @param treeNode
     * @return
     */
    private static int getCount(TreeNode treeNode) {
        if (treeNode == null) {
            return 0;
        } else {
            int left = getCount(treeNode.left);
            int right = getCount(treeNode.right);
            if (left > right) {
                return left + 1;
            } else {
                return right + 1;
            }
        }
    }

    /**
     * 測試樹 1 , 2 , 4 , 5 , 3 , 6 , 7
     * @return
     */
    private static TreeNode buildTestTree() {
        TreeNode node7 = new TreeNode(7, null, null);
        TreeNode node6 = new TreeNode(6, null, null);
        TreeNode node5 = new TreeNode(5, null, null);
        TreeNode node4 = new TreeNode(4, null, null);
        TreeNode node3 = new TreeNode(3, node6, node7);
        TreeNode node2 = new TreeNode(2, node4, node5);
        TreeNode node1 = new TreeNode(1, node2, node3);
        return node1;
    }

    /**
     * 遍歷樹
     * @param treeNode
     */
    private static void printTree(TreeNode treeNode) {
        System.out.print(treeNode.value);

        if (treeNode.left != null) {
            System.out.print(" , ");
            printTree(treeNode.left);
        }

        if (treeNode.right != null) {
            System.out.print(" , ");
            printTree(treeNode.right);
        }
    }
}
/**
 * 二分法查找
 * 給定數組 nums = {3, 6, 7, 9, 15, 20, 26, 33, 56, 63}
 * 查找目標數組 33 的下標
 */
public class TokenCode5 {
    public static void main(String[] args) {
        int[] nums = {3, 6, 7, 9, 15, 20, 26, 33, 56, 63};
        int target = 33;
        System.out.print("index = " + binarysearch(nums, target));
    }


    /**
     * 二分法查找
     *
     * @param nums
     * @param target
     * @return
     */
    private static int binarysearch(int[] nums, int target) {
        int low = 0;
        int high = nums.length - 1;
        int mid = 0;
        while (low <= high) {
            mid = (low + high) / 2;

            if (nums[mid] == target) {
                return mid;
            }
            if (nums[mid] > target) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
        return -1;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,936評論 6 535
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,744評論 3 421
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,879評論 0 381
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,181評論 1 315
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,935評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,325評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,384評論 3 443
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,534評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,084評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,892評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,067評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,623評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,322評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,735評論 0 27
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,990評論 1 289
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,800評論 3 395
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,084評論 2 375

推薦閱讀更多精彩內容