JAVA面试精选【Java算法与编程一】

  在面试中,算法题目是必须的,通过算法能够看出一个程序员的编程思维,考察对复杂问题的设计与分析能力,对问题的严谨性都能够体现出来。算法是一系列解决问题的清晰指令,也就是说,能够对一定规范的输入,在有限时间内获得所要求的输出。算法常常含有重复的步骤和一些比较或逻辑判断。如果一个算法有缺陷,或不适合于某个问题,执行这个算法将不会解决这个问题。不同的算法可能用不同的时间、空间或效率来完成同样的任务。一个算法的优劣可以用空间复杂度与时间复杂度来衡量。一个算法的好坏,直接影响一个方法调用的性能,进而影响软件的整体性能。

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

答:

packagecn.itcast;

 

import java.io.File;

import java.io.FileReader;

import java.io.FileWriter;

 

public class MainClass{

       public static voidmain(String[] args) throws Exception{

              FileManager a= new FileManager("a.txt",new char[]{'\n'});

              FileManager b= new FileManager("b.txt",new char[]{'\n',' '});        

              FileWriter c= new FileWriter("c.txt");

              String aWord= null;

              String bWord= null;

              while((aWord= a.nextWord()) !=null ){

                     c.write(aWord+ "\n");

                     bWord= b.nextWord();

                     if(bWord!= null)

                            c.write(bWord+ "\n");

              }

            

              while((bWord= b.nextWord()) != null){

                     c.write(bWord+ "\n");

              }   

              c.close();

       }

     

}

 

 

class FileManager{

 

       String[] words =null;

       int pos = 0;

       publicFileManager(String filename,char[] seperators) throws Exception{

              File f = newFile(filename);

              FileReaderreader = new FileReader(f);

              char[] buf =new char[(int)f.length()];

              int len =reader.read(buf);

              Stringresults = new String(buf,0,len);

              String regex= null;

              if(seperators.length>1 ){

                     regex= "" + seperators[0] + "|" + seperators[1];

              }else{

                     regex= "" + seperators[0];

              }

              words =results.split(regex);

       }

     

       public StringnextWord(){

              if(pos ==words.length)

                     returnnull;

              returnwords[pos++];

       }

 

}

 

  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;

import java.io.InputStream;

import java.io.OutputStream;

 

public class Jad2Java {

 

       public static voidmain(String[] args) throws Exception {

              File srcDir =new File("java");

              if(!(srcDir.exists()&& srcDir.isDirectory()))

                            thrownew Exception("目录不存在");

              File[] files= srcDir.listFiles(

                     newFilenameFilter(){

 

                                   publicboolean accept(File dir, String name) {

                                          returnname.endsWith(".java");

                                   }

                                 

                            }

              );

            

              System.out.println(files.length);

              File destDir= new File("jad");

              if(!destDir.exists())destDir.mkdir();

              for(File f:files){

                     FileInputStream  fis = new FileInputStream(f);

                     StringdestFileName = f.getName().replaceAll("\\.java$", ".jad");

                     FileOutputStreamfos = new FileOutputStream(new File(destDir,destFileName));

                     copy(fis,fos);

                     fis.close();

                     fos.close();

              }

       }

     

       private static voidcopy(InputStream ips,OutputStream ops) throws Exception{

              int len = 0;

              byte[] buf =new byte[1024];

              while((len =ips.read(buf)) != -1){

                     ops.write(buf,0,len);

              }

 

       }

}

 

由本题总结的思想及策略模式的解析:

1.

class jad2java{

       1. 得到某个目录下的所有的java文件集合

              1.1 得到目录 File srcDir = newFile("d:\\java");

              1.2 得到目录下的所有java文件:File[] files =srcDir.listFiles(new MyFileFilter());

              1.3 只想得到.java的文件: class MyFileFilterimplememyts FileFilter{

                     publicboolean accept(File pathname){

                            returnpathname.getName().endsWith(".java")

                     }

              }

            

       2.将每个文件复制到另外一个目录,并改扩展名

              2.1 得到目标目录,如果目标目录不存在,则创建之

              2.2 根据源文件名得到目标文件名,注意要用正则表达式,注意.的转义。

              2.3 根据表示目录的File和目标文件名的字符串,得到表示目标文件的File。

                     //要在硬盘中准确地创建出一个文件,需要知道文件名和文件的目录。

              2.4 将源文件的流拷贝成目标文件流,拷贝方法独立成为一个方法,方法的参数采用抽象流的形式。

                     //方法接受的参数类型尽量面向父类,越抽象越好,这样适应面更宽广。

}

 

分析listFiles方法内部的策略模式实现原理

File[] listFiles(FileFilter filter){

       File[] files =listFiles();

       //ArraylistacceptedFilesList = new ArrayList();

       File[] acceptedFiles= new File[files.length];

       int pos = 0;

       for(File file:files){

              booleanaccepted = filter.accept(file);

              if(accepted){

                     //acceptedFilesList.add(file);

                     acceptedFiles[pos++]= file;

              }          

       }

     

       Arrays.copyOf(acceptedFiles,pos);

       //return(File[])accpetedFilesList.toArray();

     

}

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

答:

       首先要了解中文字符有多种编码及各种编码的特征。

    假设n为要截取的字节数。

       public static voidmain(String[] args) throws Exception{

              String str ="我a爱中华abc我爱传智def';

              String str ="我ABC汉";

              int num =trimGBK(str.getBytes("GBK"),5);

              System.out.println(str.substring(0,num));

       }

     

       public staticint  trimGBK(byte[] buf,int n){

              int num = 0;

              booleanbChineseFirstHalf = false;

              for(inti=0;i<n;i++)

              {

                     if(buf[i]<0&& !bChineseFirstHalf){

                            bChineseFirstHalf= true;

                     }else{

                            num++;

                            bChineseFirstHalf= false;                        

                     }

              }

              return num;

       }

  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++)

{

    charch = str.charAt(i);

    if(ch>=’0’&& ch<=’9’)

    {

        digitCount++

    }

    elseif((ch>=’a’&& ch<=’z’) || (ch>=’A’ && ch<=’Z’))

    {

        engishCount++;

    }

    else

    {

        chineseCount++;

    }

}

System.out.println(……………);

 

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

这是组合设计模式。

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

代码如下:

package com.huawei.interview;

 

publicclass Node {

    public int value;

    public Node left;

    public Node right;

  

    public void store(intvalue)

    {

       if(value<this.value)

       {

           if(left ==null)

           {

              left = new Node();

              left.value=value;

           }

           else

           {

              left.store(value);

           }

       }

       else if(value>this.value)

       {

           if(right ==null)

           {

              right = new Node();

              right.value=value;

           }

           else

           {

              right.store(value);

           }        

       }

    }

  

    public boolean find(intvalue)

    { 

       System.out.println("happen" +this.value);

       if(value ==this.value)

       {

           return true;

       }

       else if(value>this.value)

       {

           if(right ==null)returnfalse;

           return right.find(value);

       }else

       {

           if(left ==null)returnfalse;

           return left.find(value);

       }

 

    }

  

    public  void preList()

    {

       System.out.print(this.value+ ",");

       if(left!=null)left.preList();

       if(right!=null) right.preList();

    }

  

    public void middleList()

    {

       if(left!=null)left.preList();

       System.out.print(this.value+ ",");

       if(right!=null)right.preList();     

    }

    public void afterList()

    {

       if(left!=null)left.preList();

       if(right!=null)right.preList();

       System.out.print(this.value+ ",");     

    } 

    public static voidmain(String [] args)

    {

       int [] data =new int[20];

       for(inti=0;i<data.length;i++)

       {

           data[i] = (int)(Math.random()*100)+ 1;

           System.out.print(data[i] +",");

       }

       System.out.println();

     

       Node root = new Node();

       root.value = data[0];

       for(inti=1;i<data.length;i++)

       {

           root.store(data[i]);

       }

     

       root.find(data[19]);

     

       root.preList();

       System.out.println();

       root.middleList();

       System.out.println();     

       root.afterList();

    }

}

-----------------又一次临场写的代码---------------------------

importjava.util.Arrays;

importjava.util.Iterator;

 

public class Node{

    private Node left;

    private Node right;

    private int value;

    //private int num;

  

    public Node(int value){

       this.value = value;

    }

    public void add(int value){

     

       if(value > this.value)

       {

           if(right != null)

              right.add(value);

           else

           {

              Node node = new Node(value);            

              right = node;

           }

       }

       else{

           if(left != null)

              left.add(value);

           else

           {

              Node node = new Node(value);            

              left = node;

           }        

       }

    }

  

    public boolean find(int value){

       if(value == this.value) return true;

       else if(value > this.value){

           if(right == null) return false;

           else return right.find(value);

       }else{

           if(left == null) return false;

           else return left.find(value);        

       }

 

    }

  

    public void display(){

       System.out.println(value);

       if(left != null) left.display();

       if(right != null) right.display();

     

    }

  

    /*public Iterator iterator(){

     

    }*/

  

    public static void main(String[] args){

       int[] values = new int[8];

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

           int num = (int)(Math.random() * 15);

           //System.out.println(num);

           //if(Arrays.binarySearch(values,num)<0)

           if(!contains(values,num))

              values[i] = num;

           else

              i--;

       }

     

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

     

       Node root = new Node(values[0]);

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

           root.add(values[i]);

       }

     

       System.out.println(root.find(13));

     

       root.display();

     

    }

  

    public static boolean contains(int [] arr,int value){

       int i = 0;

       for(;i<arr.length;i++){

           if(arr[i] == value) return true;

         

       }

       return false;

    }

  

}

posted @ 2013-12-27 23:25  elysee  阅读(7868)  评论(0编辑  收藏  举报