诸天浩瀚,神魔流转,天苍苍兮云山远,心悠悠兮梦桃源

一道Google2009夏季实习生招聘笔试程序设计题

2009-04-161,097 次阅读

最近这道题在blogjava和javaeye上出现频率很高,中午花了点时间我也实现了一下。

原题:

要求:写一个函数void count(char* input,int len),此函数的功能是计算出一个字符串中每个字符的个数,不区分大小写,输出结果时按字符在字符串中出现的先后顺序。使用程序语言不限。
例如:input="abCc*b",输出结果是a:1 b:2 c:2 *:1

我的java实现,借助了一个Map和两个List换时间,时间复杂度应该是O(n):

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;


public class Google2009 {

   public static void main(String[] args) {
        BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
        String input;
        try {
            input = sin.readLine();
            new Google2009().count(input, input.length());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void count(String input, int len){
        HashMap<Character, Integer> charMap = new HashMap<Character, Integer>();
        ArrayList<Integer> countList = new ArrayList<Integer>();
        ArrayList<Character> charList = new ArrayList<Character>();
        input = input.toLowerCase(); 
        for(int i=0; i<len; ++i){
            char c = input.charAt(i);
            if(charMap.containsKey(c)){
                int index = charMap.get(c);
                countList.set(index, countList.get(index)+1);
            }
            else {
                charList.add(c);
                countList.add(1);
                charMap.put(c, countList.size()-1);
            }
        }
        for(int i=0; i<charList.size(); ++i){
            System.out.println(charList.get(i) + ":" + countList.get(i));
        }
    }

}

作者:紫色竹简 | 分类目录:木甲工房 | 标签:

4 条评论

  1. codingliyi 说:

    类名是随便去的,我就是web前端技术太菜了,javascript基本不会,只有抓现成的来用。嗯,马上去看看,顺便把rss给改了。

  2. Jinjiang 说:

    哈哈,类名是 Google2009。
    现在不怎么写Java了,貌似用Javascript来实现还蛮简单的,也可以做算法优化的分析研究。
    另,博客搬家了,欢迎继续捧场~

  3. codingliyi 说:

    @rustingsword
    我现在变量名基本就一长串英文单词,循环内的还是用i,j一类的。Java就是类库强大,如果用C肯定就只有按ASCII码来判断了。C++现在很少用了,STL中应该有相关的函数吧。

  4. rustingsword 说:

    我写程序一直很混乱,不晓得是不是因为谭浩强的教材……变量名字都是i,j,k,x,y之类的,改回来好难。
    我还在按ASCII码人工判断大小写,太土了,对库函数一点都不熟悉。

留下评论

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>