提示:看完不如自己动手写一把验证下
前言
算法初级
有一个华为OD机试机会,我基础不好,工作经验两年,打算冲一把,时间在两个周?
记录一波。
一、问题描述
描述:
计算字符串最后一个单词的长度,单词以空格隔开,字符串长度小于5000。(注:字符串末尾不以空格为结尾)
输入描述:
输入一行,代表要计算的字符串,非空,长度小于5000。
输出描述:
输出一个整数,表示输入字符串最后一个单词的长度。
示例1
输入:
hello nowcoder
输出:
8
说明:
最后一个单词为nowcoder,长度为8
二、我的解答
1.初始粗糙版
代码如下:
using System;
using System.Linq;
namespace zifuchuanchangdu
{
class Program
{
static void Main(string[] args)
{
// line存储屏幕输入内容
string line;
while ((line = System.Console.ReadLine()) != null)
{
// 用split将字符串用空格分隔转成数组
string[] tokens = line.Split(' ');
int tCount = tokens.Count();
int Result = 0;
// 无效的分情况....
if (tCount == 1)
{
Result = tokens[0].Length;
}
else
{
Result = tokens[tCount - 1].Length;
}
Console.WriteLine(Result);
}
}
}
}
2.结合评论区大佬答案,分析自己掉的题目陷阱或者没考虑到的
1.while循环读取输入是程序自己给的,但是这个我之前没想到过,我只会原始手段,以及我那多余的分支
2.输入描述是限制输入内容,还是我自己卡控呢,咱也不懂,就当我手动卡控,显然,我不行,既没有去掉输入内容的空格,也没有限制长度
优化后的代码
public static void Main(string[] args)
{
string line;
while ((line = System.Console.ReadLine()) != null)
{
if (string.IsNullOrWhiteSpace(line.Trim()))
{
Console.WriteLine("字符串不能为空");
}
if (line.Length < 5000)
{
string[] tokens = line.Split(' ');
int tCount = tokens.Count();
int Result = 0;
Result = tokens[tCount - 1].Length;
Console.WriteLine(Result);
}
else
{
Console.WriteLine("字符串字符串长度超出限制!");
}
}
}
3.官方解法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HJ01_LastStringLength_0_OfficialSolution
{
class Program
{
public static void Main(string[] args)
{
/* 思路就是找出字符串空格位置,用长度减空格下标再减1
* 注意没有空格的情况
*/
string line;
while ((line = System.Console.ReadLine()) != null)
{
// 遍历字符
char[] c = line.ToCharArray();
// 越看越像是看封装起来的indexof方法
int index = -1;
// 思考:字符数组,Length与Count()有何不同?
for (int i = 0; i < c.Length; i++)
{
if (c[i] == ' ')
{
index = i;
}
}
System.Console.WriteLine(c.Length - index - 1);
}
}
}
}
总结
注意综合考虑题目要求,学习先进经验