[java] LeetCode32

Viewer

copydownloadembedprintName: LeetCode32
  1. class Solution { 
  2.     public String countAndSay(int n) {
  3.         String crtStr = "1"; // Base Case
  4.         for (int i = 1; i < n; i++) {
  5.             crtStr = converStr(crtStr);
  6.         }
  7.         return crtStr;
  8.     }
  9.  
  10.     private String converStr(String str) {
  11.         StringBuilder convertedStr = new StringBuilder("");
  12.         char crtChar = str.charAt(0);
  13.         int counter = 1;
  14.  
  15.         for (int i = 1; i < str.length(); i++) {
  16.             if (str.charAt(i) == str.charAt(- 1)) {
  17.                 counter++;
  18.             } else {
  19.                 convertedStr.append(counter) ;
  20.                 convertedStr.append(crtChar);
  21.                 crtChar = str.charAt(i);
  22.                 counter = 0;
  23.             }
  24.         }
  25.  
  26.         convertedStr.append(counter);
  27.         convertedStr.append(crtChar);
  28.         return convertedStr.toString();
  29.     }
  30. }
  31.  

Editor

You can edit this paste and save as new:


File Description
  • LeetCode32
  • Paste Code
  • 25 Sep-2021
  • 877 Bytes
You can Share it: