java开发工程师面试题(二)

1、n为整形的函数形参,用伪代码实现如下图案的打印:

当n=1时:

*

当n=2时:

*

**

*

当n=3时:

*

***

******

***

*

当n=4时:

*

****

********

************

********

****

*

......


答案:

package com.llb.mianshi1;

public class Demo3 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		paint(3);
	}
	
	public static void paint(int num){
		//上部分
		for(int i=1; i<=num; i++){
			if(1==i){
				System.out.print("*");
			}else if(2==i){
				for(int j=1; j<=num; j++){
					System.out.print("*");
				}
			}else{
				for(int k=1; k<=num+(i-2)*num; k++){
					System.out.print("*");
				}
			}
			System.out.println();
		}
		//下部分
		for(int i=num-1; i>=1; i--){
			if(1==i){
				System.out.print("*");
			}else if(2==i){
				for(int j=1; j<=num; j++){
					System.out.print("*");
				}
			}else{
				for(int k=1; k<=num+(i-2)*num; k++){
					System.out.print("*");
				}
			}
			System.out.println();
		}
	}
}



2、在下面这段话中,检索出出现次数最多的英文单词:
Look to the skies above London and you’ll see the usual suspects rainclouds, plane and pigeons. But by the end of the year, you might just see something else.


答案:

package com.llb.mianshi1;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Demo4 {
	public static void main(String[] args) {
		String str = "Look to the skies above London and you'll see " +
				"the usual suspects rainclouds, plane and pigeons." +
				" But by the end of the year, you might just see something else."; 
		accountWord(str);
	}
	
	public static void accountWord(String str){
		str = str.replace("\'", " ");
		str = str.replace(".", " ");
		str = str.replace(",", " ");
		String[] strings = str.split("\\s+");	//注意两个单词间有多个空格的情况,这里使用正则表达式来匹配
		Map map = new HashMap();	//用来存储单词和单词出现的次数
		List list = new ArrayList();	//用来存储strings中所有的单词(注意:strings中的单词有重复的、hashmap是通过键来访问的)
		//利用hashmap的键值存储来记录单词出现的次数
		for(String s : strings){
			//判断map中是否已经存在该单词,如果存在则把出现的次数加1,不存在则把单词加入map中并把出现次数设为1
			if(map.containsKey(s)){
				int x = map.get(s);
				x++;
				map.put(s, x);
			}else{
				map.put(s, 1);
				list.add(s);
			}
		}
		//找出出现次数最多的单词以及出现的次数
		String maxNumString = null;	//记录出现最多次数的单词
		int maxNum = 0;				//记录出现最多次数单词的出现次数
		for(String s : list){
			int x = map.get(s);
			if(x>maxNum){
				maxNumString = s;
				maxNum = x;
			}
		}
		System.out.println("出现最多的单词是:"+maxNumString);
		System.out.println("出现的次数时:"+maxNum);
	}
}





你可能感兴趣的:(面试)