笔试题-编程
抛砖引玉,还望各位大侠提供更好的方法
?
?
1.编程:通过线程每个一秒打印如下字符串:“ABCDEFG”,输出结果为:
A
AB
ABC
ABCD
ABCDE
ABCDEF
ABCDEFG
?
继承Thread:
?
?
package main;public class ThreadA extends Thread{private String A = "ABCDEFG";public void run(){try { int length = A.length(); for(int i=1;i<=length;i++){ System.out.println(A.substring(0, i)); sleep(1000); }} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}} public void a(){ }public static void main(String args[]){ThreadA ta = new ThreadA();ta.start();}}
?
实现Runnable接口
?
?
package main;public class ThreadB implements Runnable{private String A = "ABCDEFG";@Overridepublic void run() {// TODO Auto-generated method stub try { int length = A.length(); for(int i=1;i<=length;i++){ System.out.println(A.substring(0, i)); Thread.sleep(1000); }} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}} public static void main(String args[]){ ThreadB tb = new ThreadB(); Thread thread = new Thread(tb); thread.start(); }}
?
2.编程:输出打印如下字符串中各字母出现的次数,采用效率最高的一种方法 ? ?
?
方法一:效率应该低些
package main;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Map.Entry;public class HowTime {private String t = null;private String g = null;public void count(String A){Map<String, Integer> hashMap = new HashMap<String, Integer>();for(int i=1;i<=A.trim().length();i++){int time = 0;t = A.trim().substring(i-1,i);g = A.trim().substring(0,i-1);if(g.contains(t)){int count = hashMap.get(t)+1;hashMap.put(t, count);}else{hashMap.put(t, ++time);} }Iterator<Entry<String, Integer>> iterator = hashMap.entrySet().iterator();while(iterator.hasNext()){Entry<String, Integer> entry = iterator.next();int j = (Integer) entry.getValue();String h = (String) entry.getKey();System.out.println(h+"出现的次数为:"+j);}}public static void main(String args[]){long startTime=System.nanoTime(); //获取开始时间String A = "abdafasfasfaadfioewl;k asfd asdf";HowTime ht = new HowTime();ht.count(A);long endTime=System.nanoTime(); //获取结束时间System.out.println("程序运行时间: "+(endTime-startTime)+"ns");}}
方法二;效率应该稍微高些
package main;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Map.Entry;public class HowTimes {public void count(String A){Map<Character, Integer> hashMap = new HashMap<Character, Integer>();char[] a = A.toCharArray();for(int i=0;i<a.length;i++){if(hashMap.containsKey(a[i])){hashMap.put(a[i], hashMap.get(a[i])+1);}else{hashMap.put(a[i], 1);} }Iterator<Entry<Character, Integer>> iterator = hashMap.entrySet().iterator();while(iterator.hasNext()){Entry<Character, Integer> entry = iterator.next();int j = (Integer) entry.getValue();Character h = (Character) entry.getKey();System.out.println(h+"出现的次数为:"+j);}}public static void main(String args[]){long startTime=System.nanoTime(); //获取开始时间String A = "abdafasfasfaadfioewl;k asfd asdf";HowTimes ht = new HowTimes();ht.count(A);long endTime=System.nanoTime(); //获取结束时间System.out.println("程序运行时间: "+(endTime-startTime)+"ns");}}