Who knows what is wrong with my string operation? C++

  • 0
    class Solution {
        vector<string> generateAbbreviations(string word) {
            vector<string> res;
            int n = word.size();
            int bound = 1 << n;
            for (int i = 0; i < bound; i ++){
                int pattern = i;
                string str2add = "";
                int abbr_number = 0;
                for (int j = 0; j < bound; j++){
                    if ( (pattern >> j) & 1){
                        abbr_number ++;
                        if (j+1 < bound && ((pattern >> (j+1)) & 1)) continue;
                            str2add += to_string(abbr_number);
                            abbr_number = 0;
                        str2add += word[j];
            return res;

    Above is my solution to the problem. I am following the bit string pattern here to generate abbreviations. Theoretically it should work, but it is appending a lot of null characters at the end of each generated string. Can someone point out what I am doing wrong here but I didn't realize? Thanks a lot!

    Below is what I got from the judge for the test case "word".


  • 0

    found out the answer, for index j, I should use the string size n, instead of bound

Log in to reply

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