华为机试题----找一句话中最长的单词

25 篇文章 1 订阅

一、问题描述

功能描述:键盘输入一句话
               输出一句话中最常的单词,如果最长的出现多次,返回第一个。
               这句话只包含数字字母和标点。

输入:a aa,cat tiger.123dd 

输出: tiger

要求实现方法:
public String getLongString(String data)
{
    //TODO
    return "";
}


二、算法分析

1. 关键问题,如何用正则表达式来匹配标点

2. 如何判断一个子字符串里面都是字符。

其实这两个问题归于一点就是正则表达式使用。

特别要注意,正则表达式要匹配英文句号一定要加转义符号。

三、算法

public String getLongString1(String test)
	{
		String result = "";
		String[] tempStrArr = test.split(REGEX_BIAODIAN);
		int maxcount = 1;
		for (int i = 0; i < tempStrArr.length; i++) {
			if(tempStrArr[i].matches(REGEX_CHAR) && tempStrArr[i].length() > maxcount) {
				result = tempStrArr[i];
				maxcount = tempStrArr[i].length();
			}
		}
	    return result;
	}

测试类:

package com.albertshao.csi.interview;

/**
 * @author albertshao
 *
 */
public class Main9 {

	private static final String REGEX_CHAR = "^[a-z]*$";
	private static final String REGEX_BIAODIAN = "[,\\.;\\:\\s]";
	public static void main(String[] args) {
		String test = "a aa,cat tiger.123dd";
		Main9 m = new Main9();
		System.out.println(m.getLongString1(test));
		
	}
	
	public String getLongString1(String test)
	{
		String result = "";
		String[] tempStrArr = test.split(REGEX_BIAODIAN);
		int maxcount = 1;
		for (int i = 0; i < tempStrArr.length; i++) {
			if(tempStrArr[i].matches(REGEX_CHAR) && tempStrArr[i].length() > maxcount) {
				result = tempStrArr[i];
				maxcount = tempStrArr[i].length();
			}
		}
	    return result;
	}
}

运行结果:

tiger




                
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值