某大型电商集团2014年校园招聘笔试题(编程题)

编程题一:

格式化字符串,规则去除字符串头尾的空格字符,两个单词中间的空格字符只保留一个,要求不增加额外的空间,举例:字符串"   I     am a     little boy.   ",经过格式化后为“I am a little boy.”

给定的C语言函数模型为public void formatString(char[] str, int length){}


我编写的java代码如下:

方法一:

public static void formatStringOne(char[] str, int length) {
		boolean isWord = false;
		int start = 0, end = 0, wordCount = 0;
		for (int i = 0; i < length; i++) {
			if (str[i] != ' ' && isWord == false) {
				isWord = true;
				start = i;
			} else if (str[i] == ' ' && isWord == true) {
				isWord = false;
				end = i - 1;
				if (wordCount > 0) {
					System.out.print(' ');
				}
				for (int j = start; j <= end; j++) {
					System.out.print(str[j]);
				}
				wordCount++;
			}
		}
	}

方法二:

	public static void formatStringTwo(char[] str, int length) {
		boolean isWord = false;
		int wordCount = 0;
		for (int i = 0; i < length; i++) {
			if (str[i] != ' ' && isWord == false) {
				isWord = true;
				if (wordCount > 0) {
					System.out.print(' ');
				}
				wordCount++;
				System.out.print(str[i]);
			} else if (str[i] == ' ' && isWord == true) {
				isWord = false;
			} else if (str[i] != ' ' && isWord == true) {
				System.out.print(str[i]);
			}
		}
	}

其中方法二的效率比方法一高。


PS:这是我人生中的第一篇博客,欢迎大家拍砖吐槽!!


详细代码查看我的gihub

https://github.com/YongLinW

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值