JAVA interview Selection [Java Algorithm and programming I]

Source: Internet
Author: User

The keys file is separated by carriage return or space.

A:

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. Write a program, copy all. java files under the d: \ java directory to the d: \ jad directory, and change the extension of the original file from. java to. jad.

(You are working on the above question. If you are late online, please do it. You must be able to write code for these simple questions when looking for a job !)

A:The listFiles method accepts a FileFilter object. This FileFilter object is a deliberate policy object. Different people provide different FileFilter implementations, that is, different filtering policies are provided.

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 ("the directory does not exist ");

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 FCM = new FileInputStream (f );

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

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

Copy (FCM, fos );

FCM. close ();

Fos. close ();

}

}

 

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

Int len = 0;

Byte [] buf = new byte [1, 1024];

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

Ops. write (buf, 0, len );

}

 

}

}

 

Analysis of the ideas and strategies summarized in this question:

1.

Class jad2java {

1. Get all java file sets in a directory

1.1. The directory File srcDir = newFile ("d: \ java") is obtained ");

1.2 get all the java files in the directory: File [] files = srcDir. listFiles (new MyFileFilter ());

1.3 only get the. java file: class MyFileFilterimplememyts FileFilter {

Publicboolean accept (File pathname ){

Returnpathname. getName (). endsWith (". java ")

}

}

 

2. copy each file to another directory and change the extension.

2.1 obtain the target directory. If the target directory does not exist, create

2.2 obtain the target file name based on the source file name. Use a regular expression and note the escape.

2.3 obtain the File that represents the target File based on the File that represents the Directory and the string of the target File name.

// To accurately create a file on the hard disk, you need to know the file name and directory of the file.

2.4 copy the source file stream to the target file stream. The copy method becomes an independent method, and the parameters of the method are in the form of abstract streams.

// The parameter types accepted by the method are oriented to the parent class as much as possible. The more abstract the better, the wider the adaptability.

}

 

Analyze the implementation principle of the Rule mode in the listFiles Method

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. Compile a function to intercept a string. The input is a string and the number of characters, and the output is a string intercepted by byte. However, make sure that the Chinese characters are not intercepted by half, such as "my ABC ", 4. Extract "I AB", input "I abc Han DEF", and 6, and output "I abc" instead of "I ABC + Han ".

A:

First, you must understand that Chinese characters have multiple encodings and the features of various encodings.

Assume that n is the number of bytes to be truncated.

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

String str = "I love Chinese abc, I love Chuanzhi def ';

String str = "my ABC Han ";

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

{

If (buf [I] <0 &&! BChineseFirstHalf ){

BChineseFirstHalf = true;

} Else {

Num ++;

BChineseFirstHalf = false;

}

}

Return num;

}

4. There is a string that contains Chinese, English, and numeric characters. Count and print the number of characters.

A: Haha, it actually contains Chinese characters, English characters, and numbers. It was originally a smoke bullet.

String content = "zz Safi of 111 sasbbb of aadf in China ";

HashMap map = new HashMap ();

For (int I = 0; 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 ());

}

It is estimated that the student who was interviewed was not clear, and the question is likely to be:

If a string of characters such as "aaaabbc China 1512" needs to calculate the number of English characters, the number of Chinese characters, and the number of numbers respectively, it is assumed that there are no special characters except Chinese characters, English characters, and numbers.

Int engishCount;

Int chineseCount;

Int digitCount;

For (int I = 0; 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. Describe the binary tree encountered in life. Implement the binary tree using java

This is a combination design model.

I have a lot of (assuming 0.1 million) data to save, and I need to retrieve from the stored data to see if there is a certain data. (I want to explain the benefits of a binary tree, what should I do? That is to say, the disadvantages of others). If there is an array, then the number that you happen to be looking for is located at the location of 99999, the search speed will be very slow, because it will be retrieved from 1st in turn, and then compare them. Balanced binary tree (sorting is required before building a balanced binary tree, which we will not consider here) can solve this problem well, But binary tree traversal (pre-order, middle-order, and post-order) the efficiency is much lower than the array. The principle is as follows:

The Code is as follows:

PackageCom. huawei. interview;

 

PublicclassNode {

Public intValue;

PublicNode left;

PublicNode right;

 

Public voidStore (IntValue)

{

If(Value <This. Value)

{

If(Left =Null)

{

Left =NewNode ();

Left. value = value;

}

Else

{

Left. store (value );

}

}

Else if(Value>This. Value)

{

If(Right =Null)

{

Right =NewNode ();

Right. value = value;

}

Else

{

Right. store (value );

}

}

}

 

Public booleanFind (IntValue)

{

System.Out. Println ("happen" +This. Value );

If(Value =This. Value)

{

Return true;

}

Else if(Value>This. Value)

{

If(Right =Null)Returnfalse;

ReturnRight. find (value );

}Else

{

If(Left =Null)Returnfalse;

ReturnLeft. find (value );

}

 

}

 

Public voidPreList ()

{

System.Out. Print (This. Value + ",");

If(Left! =Null) Left. preList ();

If(Right! =Null) Right. preList ();

}

 

Public voidMiddleList ()

{

If(Left! =Null) Left. preList ();

System.Out. Print (This. Value + ",");

If(Right! =Null) Right. preList ();

}

Public voidAfterList ()

{

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 [I] = (Int) (Math.Random() * 100) + 1;

System.Out. Print (data [I] + ",");

}

System.Out. Println ();

 

Node root =NewNode ();

Root. value = data [0];

For(IntI = 1; I

{

Root. store (data [I]);

}

 

Root. find (data [19]);

 

Root. preList ();

System.Out. Println ();

Root. middleList ();

System.Out. Println ();

Root. afterList ();

}

}

----------------- Code written on site again ---------------------------

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

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

If (arr [I] = value) return true;

 

}

Return false;

}

 

}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.