java面试题汇总(二)----算法与编程

本文集合了一系列Java编程挑战,包括文件操作、字符串处理、数据结构、递归算法、排序算法等,通过实际代码示例展示了如何解决常见问题,是提升Java编程技能的实用资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、编写一个程序,将a.txt文件中的单词与b.txt文件中的单词交替合并到c.txt文件中,a.txt文件中的单词用回车符分隔,b.txt文件中用回车或空格进行分隔。

答:

package com.bwie.interview;

 

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintStream;

import java.util.StringTokenizer;

 

public class AnswerB01 {

 

    public static void main(String[] args) throws IOException {

        StringTokenizer tokenizer1 = getTokenzer("/a.txt");

        StringTokenizer tokenizer2 = getTokenzer("/b.txt");

        PrintStream out = new PrintStream("C:/c.txt");

        while (tokenizer1.hasMoreTokens() && tokenizer2.hasMoreTokens()) {

            out.println(tokenizer1.nextToken());

            out.println(tokenizer2.nextToken());

        }

        out.close();

    }

 

    private static StringTokenizer getTokenzer(String fileName) throws IOException {

        InputStreamReader reader = new InputStreamReader(AnswerB01.class.getResourceAsStream(fileName));

        StringBuilder builder = new StringBuilder(1000);

        int length = -1;

        char[] cs = new char[1024];

        while ((length = reader.read(cs)) != -1) {

            builder.append(cs, 0, length);

        }

        reader.close();

        return new StringTokenizer(builder.toString());

    }

}

 

2、编写一个程序,将d:\java目录下的所有.java文件复制到d:\jad目录下,并将原来文件的扩展名从.java改为.jad。

(大家正在做上面这道题,网上迟到的朋友也请做做这道题,找工作必须能编写这些简单问题的代码!)

答:listFiles方法接受一个FileFilter对象,这个FileFilter对象就是过虑的策略对象,不同的人提供不同的FileFilter实现,即提供了不同的过滤策略。

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.FilenameFilter;

import java.io.IOException;

 

public class AnswerB02 {

 

    public static void main(String[] args) throws IOException {

        File sourceFolder = new File("D:/java");

        File[] files = sourceFolder.listFiles(new JavaFileFilter());

        for (File file : files) {

            String absolutePath = file.getName();

            String targetFile = "D:/jad/" + absolutePath.substring(0, absolutePath.length() - 5) + ".jad";

            copy(file, new File(targetFile));

        }

    }

 

    private static void copy(File source, File target) throws IOException {

        FileInputStream input = new FileInputStream(source);

        FileOutputStream out = new FileOutputStream(target);

        int length = -1;

        byte[] bs = new byte[1024];

        while ((length = input.read(bs)) != -1) {

            out.write(bs, 0, length);

        }

        input.close();

        out.close();

    }

   

private static final class JavaFileFilter implements FilenameFilter {

        @Override

        public boolean accept(File dir, String name) {

            return name.endsWith(".java");

        }

    }

}

3、编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串,但要保证汉字不被截取半个,如“我ABC”,4,应该截取“我AB”,输入“我ABC汉DEF”,6,应该输出“我ABC”,而不是“我ABC+汉的半个”。

import java.io.IOException;

 

public class AnswerB03 {

    public static void main(String[] args) throws IOException {

        String s = "我ABC汉DEF";

        System.out.println(substring(s, 6));

    }

    public static String substring(String s, int length) {

        char[] cs = s.toCharArray();

        StringBuilder builder = new StringBuilder();

        int count = 0;

        for (char c : cs) {

            if (isAsc(c)) {

                count++;

            } else {

                count += 2;

            }

            if (count > length) {

                break;

            }

            builder.append(c);

        }

        return builder.toString();

    }

    public static boolean isAsc(char c) {

        return c < 128;

    }

}

 4、有一个字符串,其中包含中文字符、英文字符和数字字符,请统计和打印出各个字符的个数。

答:哈哈,其实包含中文字符、英文字符、数字字符原来是出题者放的烟雾弹。

String content = "中国aadf的111萨bbb菲的zz萨菲";

HashMap map = new HashMap();

for (int i = 0; i < content.length; i++) {

    char c = content.charAt(i);

    Integer num = map.get(c);

    if (num == null)

        num = 1;

    else

        num = num + 1;

    map.put(c, num);

}

for (Map.EntrySet entry : map) {

    system.out.println(entry.getkey() + ":" + entry.getValue());

}

估计是当初面试的那个学员表述不清楚,问题很可能是:

如果一串字符如"aaaabbc中国1512"要分别统计英文字符的数量,中文字符的数量,和数字字符的数量,假设字符中没有中文字符、英文字符、数字字符之外的其他特殊字符。

int engishCount;

int chineseCount;

int digitCount;

for (int i = 0; i < str.length; i++) {

    char ch = str.charAt(i);

    if (ch >= '0' && ch <= '9') {

        digitCount++;

    } else if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {

        engishCount++;

    } else {

        chineseCount++;

    }

}

5、说明生活中遇到的二叉树,用java实现二叉树

这是组合设计模式。

我有很多个(假设10万个)数据要保存起来,以后还需要从保存的这些数据中检索是否存在某个数据,(我想说出二叉树的好处,该怎么说呢?那就是说别人的缺点),假如存在数组中,那么,碰巧要找的数字位于99999那个地方,那查找的速度将很慢,因为要从第1个依次往后取,取出来后进行比较。平衡二叉树(构建平衡二叉树需要先排序,我们这里就不作考虑了)可以很好地解决这个问题,但二叉树的遍历(前序,中序,后序)效率要比数组低很多,原理如下图:

代码如下:

public class AnswerB04 {

 

    public static void main(String[] args) {

        Node root = makeupTree();

        traverse(root);

    }

 

    private static void traverse(Node node) {

        if (node == null) {

            return;

        }

        traverse(node.left);

        System.out.println(node.value);

        traverse(node.right);

    }

 

    private static Node makeupTree() {

        Node root = new Node(0);

        Node node1 = new Node(1);

        Node node2 = new Node(2);

        Node node11 = new Node(11);

        Node node12 = new Node(12);

        Node node21 = new Node(21);

        Node node22 = new Node(22);

 

        root.left = node1;

        root.right = node2;

 

        node1.left = node11;

        node1.right = node12;

 

        node2.left = node21;

        node2.right = node22;

        return root;

    }

 

    public static class Node {

        public Node left;

        public Node right;

        public int value;

 

        public Node(int value) {

            this.value = value;

        }

    }

}

8、递归算法题1

一个整数,大于0,不用循环和本地变量,按照n,2n,4n,8n的顺序递增,当值大于5000时,把值按照指定顺序输出来。

例:n=1237

则输出为:

1237

2474

4948

9896

9896

4948

2474

1237

提示:写程序时,先致谢按递增方式的代码,写好递增的以后,再增加考虑递减部分。

public static void doubleNum(int n) {

    System.out.println(n);

    if (n <= 5000)

        doubleNum(n * 2);

    System.out.println(n);

}

 

Gaibaota(N) = Gaibaota(N-1) + n

 

9、递归算法题2

第1个人10,第2个比第1个人大2岁,依次递推,请用递归方式计算出第8个人多大?

package cn.itcast;

 

import java.util.Date;

 

public class A1 {

 

    public static void main(String[] args) {

        System.out.println(computeAge(8));

    }

 

    public static int computeAge(int n) {

        if (n == 1)

            return 10;

        return computeAge(n - 1) + 2;

    }

}

 

public static void toBinary(int n, StringBuffer result) {

    if (n / 2 != 0)

        toBinary(n / 2, result);

    result.append(n % 2);

}

10、排序都有哪几种方法?请列举。用JAVA实现一个快速排序。

本人只研究过冒泡排序、选择排序和快速排序,下面是快速排序的代码:

冒泡排序:

private static void bubbleSort(int[] array) {

    for (int i = 1; i < array.length; i++) {

        for (int j = 0; j < i; j++) {

            if (array[i] < array[j]) {

                int temp = array[i];

                array[i] = array[j];

                array[j] = temp;

            }

        }

    }

}

 

快速排序:

public class QuickSort {

    public void quickSort(String[] strDate, int left, int right) {

        String middle, tempDate;

        int i, j;

        i = left;

        j = right;

        middle = strDate[(i + j) / 2];

        do {

            while (strDate[i].compareTo(middle) < 0 && i < right)

                i++; // 找出左边比中间值大的数

            while (strDate[j].compareTo(middle) > 0 && j > left)

                j--; // 找出右边比中间值小的数

            if (i <= j) { // 将左边大的数和右边小的数进行替换

                tempDate = strDate[i];

                strDate[i] = strDate[j];

                strDate[j] = tempDate;

                i++;

                j--;

            }

        } while (i <= j); // 当两者交错时停止

 

        if (i < right) {

            quickSort(strDate, i, right);

        }

        if (j > left) {

            quickSort(strDate, left, j);

        }

    }

 

    public static void main(String[] args) {

        String[] strVoid = new String[] { "11", "66", "22", "0", "55", "22", "0", "32" };

        QuickSort sort = new QuickSort();

        sort.quickSort(strVoid, 0, strVoid.length - 1);

        for (int i = 0; i < strVoid.length; i++) {

            System.out.println(strVoid[i] + " ");

        }

    }

}

11、有数组a[n],用java代码将数组元素顺序颠倒

public class AnswerB11 {

 

    public static void main(String[] args) {

        int[] array = { 2, 25, 21, 63, 234, 83 };

        reverse(array);

        System.out.println(Arrays.toString(array));

    }

 

    private static void reverse(int[] array) {

        for (int i = 0; i < array.length / 2; i++) {

            int temp = array[i];

            array[i] = array[array.length - 1 - i];

            array[array.length - 1 - i] = temp;

        }

    }

}

12 不使用递归遍历二叉树

import java.util.Stack;

 

public class AnswerB13 {

 

    public static void main(String[] args) {

        Node tree = makeupTree();

        Stack<Node> stack = new Stack<Node>();

        Node currentNode = tree;

        while (currentNode != null) {

            System.out.println(currentNode.value);

            stack.push(currentNode);

            currentNode = currentNode.left;

            if (currentNode == null) {

                Node parent = stack.pop();

                currentNode = parent.right;

                if (currentNode == null) {

                   if (stack.isEmpty()) {

                       break;

                   }

                   Node parentParent = stack.pop();

                   currentNode = parentParent.right;

                }

            }

        }

    }

 

    private static Node makeupTree() {

        Node root = new Node(0);

        Node node1 = new Node(1);

        Node node2 = new Node(2);

        Node node11 = new Node(11);

        Node node12 = new Node(12);

        Node node21 = new Node(21);

        Node node22 = new Node(22);

 

        root.left = node1;

        root.right = node2;

 

        node1.left = node11;

        node1.right = node12;

 

        node2.left = node21;

        node2.right = node22;

        return root;

    }

 

    public static class Node {

        public Node left;

        public Node right;

        public int value;

 

        public Node(int value) {

            this.value = value;

        }

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值