java - Time Complexity of while loop in case of while(boolean)? -
i trying understand time complexity calculation of function stuck @ point. unlike for loop while loop shown in code below depend on input string length. how calculate time complexity such cases?
the function
blockquote
input data: 4gopi7krishna3msc5india
output data: {"4":"gopi","7":"krishna","3":"msc","5":"india"}
input data , length may vary each , every time.
public static string splitdata(string input) { try { string outputjson = "{"; boolean run = true; while (run) { string firstchar = string.valueof(input.charat(0)); int length = integer.parseint(firstchar); if (length > 0) { string data = input.substring(1, (length + 1)); outputjson = outputjson + "\"" + string.valueof(length) + "\":\"" + data + "\""; if (length + 1 == input.length()) { run = false; outputjson = outputjson + "}"; system.out.println("tag " + length + " length " + length + " data " + data + " input " + input); } else { outputjson = outputjson + ","; input = input.substring(length + 1, input.length()); system.out.println("tag " + length + " length " + length + " data " + data + " input " + input); } } else //if input not valid make return json null { run = false; outputjson = "invalid input"; } } return outputjson; } catch (exception e) { e.printstacktrace(); return "invalid input"; } }
complexity depends on number of possible operations before execution ends, loop wouldn't faster if don't change done inside. function simpler , faster using string manipulation functions
public static void main(string args[]){ string s = "4gopi7krishna3msc5india"; string res = ""; string sp[] = s.split("[0-9]+"); res += "{"; (int = 0; i<sp.length; i++){ string sss = sp[i]; if(sss.length()==0) continue; res += "\""+sss+"\":\""+integer.tostring(sss.length())+"\"" ; res += (i == (sp.length - 1))?"":","; } res+="}"; system.out.println(res); }
Comments
Post a Comment