[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”字符。所以必须在循环之中加测指针是否移动到了最后一个字符。
这道题需要使用到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); } }
相关文章推荐
- Java for LeetCode 038 Count and Say
- [leetcode-38]count and say(java)
- [leetcode][string] Count and Say
- [LeetCode][Java] Count and Say
- LeetCode-38-Count and Say Python的int_to_string
- Java [leetcode 38]Count and Say
- **(leetcode_string) Count and Say
- 【LeetCode-面试算法经典-Java实现】【038-Count and Say(计数和表述)】
- LeetCode : Count and Say [java]
- 使用Retrofit时出现 java.lang.IllegalArgumentException: URL query string "t={type}&p={page}&size={count}" must not have replace block. For dynamic query parameters use @Query.异常原因
- LeetCode 38 : Count and Say (Java)
- leetcode:Interleaving String 使用动态规划求解的java源代码
- LeetCode 38 Count and Say(C,C++,Java,Python)
- leetcode_38题——Count and Say(string,迭代计数)
- [Leetcode] Count and Say (Java)
- JAVA String.format 方法使用介绍
- JAVA String.format 方法使用介绍
- 我学习使用java的一点体会
- JAVA学习提高之---- String.split(String,int)使用
- JAVA String.format 方法使用介绍