My working c# solution


  • 0
    S
     public IList<string> GenerateAbbreviations(string word) {
            
        List<string> res = new List<string>();
            char[] c = word.ToCharArray();
            buildWord(c, "", 0, 0, res);
            return res;
        }
        
        private void buildWord(char[] c, string b, int wp, int count, List<string> res)
        {
            if(wp >= c.Length)
            {
                if(count>0)
                    b= b+count;
                res.Add(b);
                return;
            }
            
            //no abbreviation
            if(count > 0)
                buildWord(c, b + count + c[wp], wp+1, 0, res );
            else 
                buildWord(c, b + c[wp], wp+1, 0, res);
            //abbreviation
            buildWord(c, b, wp+1, count+1, res);
        }

  • 0
        public IList<string> GenerateAbbreviations(string word) 
        {
            List<string> list = new List<string>();
            Gen(word, 0, list, new StringBuilder(), false);
            return list;
        }
        
        public void Gen(string word, int index, List<string> list, StringBuilder sb, bool lastWasNum)
        {
            if (index == word.Length)
            {
                list.Add(sb.ToString());
                return;
            }
            
            sb.Append(word[index]);
            Gen(word, index + 1, list, sb, false);
            sb.Length--;
            
            if (!lastWasNum)
            {  
                for (int cnt = 1; cnt <= word.Length - index; cnt++)
                {
                    string s = cnt.ToString();
                    sb.Append(s);
                    Gen(word, index + cnt, list, sb, true);
                    sb.Length -= s.Length;
                    
                }
            }
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.