c# - C# 字符串压缩
问题描述
我需要制作 amethod
作为string
参数并返回 astring
作为结果;
public static string Compress(string test){}
无法真正用文字描述此方法需要做什么,所以这里是输入/输出示例:
输入参数:ssdwwwweehh
输出结果:s2d1w4e2h1
我试过的是这样的:
static string Compression(string test)
{
string result = string.Empty;
for (int i = 0; i < test.Length; i++)
{
int counter = 1;
for (int j = i+1; j < test.Length; j++)
{
if (test[i] == test[j])
{
counter++;
}
else
{
i = j-1;
break;
}
}
result += test[helper] + counter.ToString();
}
return result;
}
我得到的结果是s2d1w4e2h2h1
。所以我想问题是当我的方法到达给定单词的末尾时。我该如何处理/解决这个问题?此外,我愿意接受有关更好解决方案的建议,因为我不确定这是解决它的最佳方法。
解决方案
好的,我猜对了。int helper = i;
由于在第二个循环中i
丢失,在声明中必须执行。 for
else
回答:
static string Compression(string test)
{
string result = string.Empty;
for (int i = 0; i < test.Length; i++)
{
int helper = i;
int counter = 1;
for (int j = i+1; j < test.Length; j++)
{
if (test[i] == test[j])
{
counter++;
if(j == test.Length - 1)
{
return result += test[helper] + counter.ToString();
}
}
else
{
i = j-1;
break;
}
}
result += test[helper] + counter.ToString();
}
return result;
}
推荐阅读
- python - 重塑数据框以提取特定结果
- python - python pandas在数据框列中添加列表作为默认值
- node.js - Nodejs WebService 数据库选择
- javascript - 如何将多个输入添加到对象以在 ReactJS 中呈现
- sql - 如何从与 FK 链接的两个不同表中删除记录?SQL
- python-2.7 - python 2.7 如何使超类和子类使用的函数具有自己的属性而不会出现属性错误?
- excel - 在 Ecel 中连接复选框响应
- html - 溢出滚动在班级孩子中不起作用
- mysql - 将数据导入处理程序添加到 ColdFusion 2016 Solr
- c# - 如何从 .csv 文件中删除损坏的数据?