Skip to content Navigation Menu Toggle navigation Sign in Appearance settings PlatformAI CODE CREATIONGitHub CopilotWrite better code with AIGitHub Copilot appDirect agents from issue to mergeMCP RegistryNewIntegrate external toolsDEVELOPER WORKFLOWSActionsAutomate any workflowCodespacesInstant dev environmentsIssuesPlan and track workCode ReviewManage code changesAPPLICATION SECURITYGitHub Advanced SecurityFind and fix vulnerabilitiesCode securitySecure your code as you buildSecret protectionStop leaks before they startEXPLOREWhy GitHubDocumentationBlogChangelogMarketplaceView all featuresSolutionsBY COMPANY SIZEEnterprisesSmall and medium teamsStartupsNonprofitsBY USE CASEApp ModernizationDevSecOpsDevOpsCI/CDView all use casesBY INDUSTRYHealthcareFinancial servicesManufacturingGovernmentView all industriesView all solutionsResourcesEXPLORE BY TOPICAISoftware DevelopmentDevOpsSecurityView all topicsEXPLORE BY TYPECustomer storiesEvents & webinarsEbooks & reportsBusiness insightsGitHub SkillsSUPPORT & SERVICESDocumentationCustomer supportCommunity forumTrust centerPartnersView all resourcesOpen SourceCOMMUNITYGitHub SponsorsFund open source developersPROGRAMSSecurity LabMaintainer CommunityAcceleratorGitHub StarsArchive ProgramREPOSITORIESTopicsTrendingCollectionsEnterpriseENTERPRISE SOLUTIONSEnterprise platformAI-powered developer platformAVAILABLE ADD-ONSGitHub Advanced SecurityEnterprise-grade security featuresCopilot for BusinessEnterprise-grade AI featuresPremium SupportEnterprise-grade 24/7 supportPricing Search or jump to... Search code, repositories, users, issues, pull requests... Search Clear Search syntax tips Provide feedback We read every piece of feedback, and take your input very seriously. Include my email address so I can be contacted Saved searches Use saved searches to filter your results more quickly Name Query To see all available qualifiers, see our documentation. Sign in Sign up Appearance settings Resetting focus You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session. Dismiss alert {{ message }} rajeevranjancom / Leetcode_Java Public Notifications You must be signed in to change notification settings Fork 0 Star 0 Code Issues 0 Pull requests 0 Actions Projects Security and quality 0 Insights Additional navigation options Code Issues Pull requests Actions Projects Security and quality Insights FilesExpand file tree masterBreadcrumbsLeetcode_Java/394_DecodeString394.javaCopy pathBlameMore file actionsBlameMore file actions Latest commit HistoryHistoryHistory180 lines (162 loc) · 5.17 KB masterBreadcrumbsLeetcode_Java/394_DecodeString394.javaCopy pathTopFile metadata and controlsCodeBlame180 lines (162 loc) · 5.17 KBRawCopy raw fileDownload raw fileOpen symbols panelEdit and raw actions123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180/** * Given an encoded string, return it's decoded string. * * The encoding rule is: k[encoded_string], where the encoded_string inside the * square brackets is being repeated exactly k times. Note that k is guaranteed * to be a positive integer. * * You may assume that the input string is always valid; No extra white spaces, * square brackets are well-formed, etc. * * Furthermore, you may assume that the original data does not contain any * digits and that digits are only for those repeat numbers, k. For example, * there won't be input like 3a or 2[4]. * * Examples: * * s = "3[a]2[bc]", return "aaabcbc". * s = "3[a2[c]]", return "accaccacc". * s = "2[abc]3[cd]ef", return "abcabccdcdcdef". * */ public class DecodeString394 { public String decodeString(String s) { StringBuilder sb = new StringBuilder(""); int i = 0; StringBuilder num = new StringBuilder(""); while (i < s.length()) { char c = s.charAt(i); if (c >= '0' && c <= '9') { num.append(c); i++; continue; } if (c == '[') { Res res = decodeString(s, i); int next = res.next; String in = res.in; for (int j = 0; j<Integer.parseInt(num.toString()); j++) { sb.append(in); } num = new StringBuilder(""); i = next; continue; } if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { sb.append(c); i++; continue; } } return sb.toString(); } public Res decodeString(String s, int start) { StringBuilder sb = new StringBuilder(""); int i = start+1; StringBuilder num = new StringBuilder(""); while (i < s.length()) { char c = s.charAt(i); if (c >= '0' && c <= '9') { num.append(c); i++; continue; } if (c == '[') { Res res = decodeString(s, i); int next = res.next; String in = res.in; for (int j = 0; j<Integer.parseInt(num.toString()); j++) { sb.append(in); } num = new StringBuilder(""); i = next; continue; } if (c == ']') { return new Res(i+1, sb.toString()); } if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { sb.append(c); i++; continue; } } return new Res(i+1, sb.toString()); } class Res { int next; String in; Res (int next, String in) { this.next = next; this.in = in; } } /** * https://discuss.leetcode.com/topic/57318/java-simple-recursive-solution */ public String decodeString2(String s) { if (s.length() == 0) return ""; StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i ++) { char c = s.charAt(i); if (Character.isDigit(c)) { int digit_begin = i; while (s.charAt(i) != '[') i++; int num = Integer.valueOf(s.substring(digit_begin, i)); int count = 1; int str_begin = i+1; i ++; while (count != 0) { if (s.charAt(i) == '[') count ++; else if (s.charAt(i) == ']') count --; i ++; } i--; String str = decodeString(s.substring(str_begin, i)); for (int j = 0; j < num; j ++) { sb.append(str); } } else { sb.append(c); } } return sb.toString(); } /** * https://discuss.leetcode.com/topic/57159/simple-java-solution-using-stack */ public String decodeString3(String s) { String res = ""; Stack<Integer> countStack = new Stack<>(); Stack<String> resStack = new Stack<>(); int idx = 0; while (idx < s.length()) { if (Character.isDigit(s.charAt(idx))) { int count = 0; while (Character.isDigit(s.charAt(idx))) { count = 10 * count + (s.charAt(idx) - '0'); idx++; } countStack.push(count); } else if (s.charAt(idx) == '[') { resStack.push(res); res = ""; idx++; } else if (s.charAt(idx) == ']') { StringBuilder temp = new StringBuilder (resStack.pop()); int repeatTimes = countStack.pop(); for (int i = 0; i < repeatTimes; i++) { temp.append(res); } res = temp.toString(); idx++; } else { res += s.charAt(idx++); } } return res; }} You can’t perform that action at this time.