Wednesday, February 18, 2015

String Character Count (String)

Question: a#3bd#5 -》 aaabddddd..

Idea: Since the number after # may be zero or numbers larger than 9, we need to take care of the corner cases a little bit.
Use a stringbuilder to cache the result and use a pointer to scan from left to right. If it is a letter, append to the stringbuilder; if it is a '#', temporally store the last character in the stringbuilder, pop the last character, count the number to append, append them and move the pointer forward.

Time: O(n) Space: O(1)

Code:
      public StringConvert()  
      {  
           String input1="a#3bd#5e#33";  
           System.out.println(stringExpand(input1));  
      }  
      public String stringExpand(String s)  
      {  
           if(s==null||s.length()==0)  
                return s;  
           StringBuilder builder=new StringBuilder();  
           for(int i=0;i<s.length();)  
           {  
                char c=s.charAt(i);  
                if(getType(c)==3)  
                {  
                     builder.append(c);  
                     i++;  
                }  
                else  
                {  
                     int num=0;  
                     char lastC=builder.charAt(builder.length()-1);  
                     int j=i;  
                     for(j=i+1;j<s.length()&&getType(s.charAt(j))==2;j++)  
                     {  
                          num=num*10+(int)(s.charAt(j)-'0');  
                     }  
                     builder.deleteCharAt(builder.length()-1);  
                     for(int k=0;k<num;k++)  
                          builder.append(lastC);  
                     i=j;  
                }  
           }  
           return builder.toString();  
      }  
      public int getType(char c)  
      {  
           if(c=='#')  
                return 1;  
           if(c>='0'&&c<='9')  
                return 2;  
           else  
                return 3;  
      }  

No comments:

Post a Comment