Chinaunix首页 | 论坛 | 博客
  • 博客访问: 7423
  • 博文数量: 13
  • 博客积分: 520
  • 博客等级: 中士
  • 技术积分: 140
  • 用 户 组: 普通用户
  • 注册时间: 2010-04-15 15:29
文章分类
文章存档

2010年(13)

我的朋友
最近访客

分类:

2010-04-15 17:37:04

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

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

本人实现的Java版本如下:
public class CountTest {

    
public static void main(String[] args) {
        String input
="abCc*b";
        count(input,
6);
    }
    
    
private static void count(String input,int len){
        String strVisited
=null;
        
int num=0;
        
for(int i=0;i<len;i++){
            
char ch=Character.toLowerCase(input.charAt(i));
            
if(strVisited==null){
                strVisited
+=ch;
            }
else if(strVisited.indexOf(ch)==-1){
                strVisited
+=ch;
            }
else{
                
continue;
            }
            
for(int j=0;j<len;j++){
                
if(Character.toLowerCase(input.charAt(j))==ch)
                    num
++;
            }
            System.out.print(ch
+":"+num+" ");
            num
=0;
        }
    }
}

C++版本如下:
#include <stdlib.h>
#include 
<iostream>
#include 
<string>
#include 
<cctype>

using namespace std;

void count(char *input, int len) {
    
string strVisited;
    
int num = 0;
    
for (int i = 0; i < len; i++) {
        
char ch = tolower(input[i]);
        
if (strVisited.empty()) {
            strVisited 
+= ch;
        } 
else if (strVisited.find(ch, 0== string::npos) {
            strVisited 
+= ch;
        } 
else {
            
continue;
        }
        
for (int j = 0; j < len; j++) {
            
if (tolower(input[j]) == ch)
                num
++;
        }
        cout 
<< ch << ":" << num << " ";
        num 
= 0;
    }
}

int main(int argc, char** argv) {
    
string input="abCc*b";
    count((
char*)input.c_str(),6);
    
return (EXIT_SUCCESS);
}
 
//Only consider ASCII
    //Author:Yvon
    //
    public static void count(String input,int len)
    {
        int counts[]=new int[255];
        char orders[]=new char[255];
        int nextChPos=0;
        
        for(int i=0;i        {
            char lowerCase=Character.toLowerCase(input.charAt(i));
                      
            //do not need track more than once
            if( counts[lowerCase&0xff]++==0)
            {
                orders[nextChPos]=lowerCase;
                nextChPos=lowerCase&0xff;
            }
            
        }
        
        for(char c=orders[0];c>0;)
        {
            System.out.println(c+":"+counts[(c&0xff)]);
            c=orders[c];
        }
    }
阅读(148) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~