标签:count 38 string int res say num str
目录
题目链接
https://leetcode.com/problems/count-and-say/
注意点
整数序列中的每一项将表示为一个字符串,需要注意类型转换。
解法
解法1:暴力解法无优化。每次输入一个整数都从数字1起计算一遍。具体过程为:写一个read函数,输入一个字符串,模拟读字符串的过程,输出该字符串的读法。num变量记录当前数字,count变量记录这个数字出现了几次。第二个数字起,从左到右遍历一遍。若与前一个数字相同,则计数count加一;若不同,则在字符串后插入计数值num和存储数值count,并将存储数值num改为当前数字,count置为1。
string read(string str){
string res = "";
int len = str.length();
if(str == "1") return "11";
int count = 1;
char num = str[0];
char temp;
int i = 1;
for(i = 1; i < len-1;i++)
{
if(str[i] == num)
{
count++;
}
else
{
temp = count + '0';
res = res + temp + num;
num = str[i];
count = 1;
}
}
if (str[i] == str[i-1])
{
count++;
temp = count + '0';
res = res + temp + num;
}
else
{
temp = count + '0';
res = res + temp + num;
res = res + "1" + str[i];
}
return res;
}
string countAndSay(int n){
string res = "1";
while(--n)
{
res = read(res);
}
return res;
}
解法2:调整了解法1中read函数的处理逻辑。同样从左往右遍历一遍,若与后一个数相同,计数值count加1;若不同,将计数值和当前位置数值插入字符串,同时重置计数值。为了防止最后一位比较时出现错误,在原字符串末尾添加了一个字符"x"用于比较。
执行用时 :
4 ms, 在所有 C++ 提交中击败了85.15%的用户
内存消耗 :6.7 MB, 在所有 C++ 提交中击败了100.00%的用户
string read(string str){
if(str == "1") return "11";
str = str + "x";
string res = "";
int index = 0;
int count = 1;
while(index < str.length()-1){
while(str[index] == str[index+1])
{
index++;
count++;
}
res += count + '0';
res += str[index];
count = 1;
index++;
}
return res;
}
string countAndSay(int n){
string res = "1";
while(--n){
res = read(res);
}
return res;
}
测试代码
#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;
int main()
{
int num = 0;
while(scanf("%d",&num)!= EOF)
{
cout<<countAndSay(num)<<endl;
}
return 0;
}
遇到问题
1.string类型变量末尾插入int型数字:
res += count + '0';
小结
字符串处理过程中注意类型转换以及数组越界问题。
标签:count,38,string,int,res,say,num,str 来源: https://www.cnblogs.com/ChenYujin/p/12913546.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。