[LeetCode] Count and Say (使用java string 体会)

原题:https://oj.leetcode.com/problems/count-and-say


这道题需要使用到string。但是在c++中的string与java中的是不一样的。Java中的String比并不能直接访问到最后一个“\0”字符。所以必须在循环之中加测指针是否移动到了最后一个字符。


import java.util.*;
import java.lang.*;

class Solution{
	public String countAndSay(int n){
		String output = new String("1");
		if(n == 0) return "";
		
		for(int i = 0; i <= n; i++)
		{	
			System.out.println("loop number " + i + ". Output now is " + output + ". Before enter.");	
			output = say(output);
			System.out.println("After enter. Output new is: " + output + "\n");
		}

		return output;
	}

	public String say(String output){	
		System.out.println("Enter say(). Output now is " + output);
		int len = output.length();
		System.out.println("The length of output now is " + len);
		int count = 1;
		String curStr = new String("");	
		char tmp = output.charAt(0);

		if(len == 1)
		{
			curStr += count;
			curStr += output.charAt(0);
		}	

		for(int i = 1; i <= len; i++)
		{
			if(tmp == output.charAt(i))
			{	
				System.out.println("Now tmp is " + tmp + "and char(" + i + ") is " + output.charAt(i));
				count++;
			}
			else 	
			{
				curStr += count;
				curStr += output.charAt(i - 1);
				count = 1;
				tmp = output.charAt(i);
			}	
			//if(i == len - 1)
			//{
			//	curStr += count;
			//	curStr += output.charAt(i);
			//}	
		}

		

		return curStr;
	}
	
/*	public static void main(){
		Solution sln = new Solution();
		String res = sln.countAndSay(5);
		System.out.println(res); 	
	}*/
}

public class test{
	static public void main(String args[]){
		Solution sln = new Solution();
		//String res = new String("1");
		//char a = res.charAt(0);
		String res = sln.countAndSay(5);
		System.out.println(res); 
	}	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值