zoukankan      html  css  js  c++  java
  • 【LeetCode】38. count-and-say

    题目链接

    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';
    

    小结

    字符串处理过程中注意类型转换以及数组越界问题。

  • 相关阅读:
    HDU 3695 Computer Virus on Planet Pandora
    codeforces 706D Vasiliy's Multiset
    HDU 2222 Keywords Search
    POJ 2348 Euclid's Game
    HDU 1079 Calendar Game
    js选项卡的实现方法
    实现鼠标悬浮切换标题和内容
    js实现鼠标悬浮切换 setTab 代码实现
    自学Node.js: WebStorm+Node.js开发环境的配置
    windows 下安装nodejs
  • 原文地址:https://www.cnblogs.com/ChenYujin/p/12913546.html
Copyright © 2011-2022 走看看