您的位置:首页 > 编程语言 > Java开发

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

2014-12-31 14:06 316 查看
原题: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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: