Krononberg

leetcode 1859. Sorting the Sentence.cpp 본문

개발 로그/알고리즘

leetcode 1859. Sorting the Sentence.cpp

k._. 2021. 6. 21. 23:50
class Solution {
public:
    string sortSentence(string s) {
        //sentence를 word로 쪼개어 vector<string>으로 저장
            vector<string>tempVec;
            for (int i = 0; i < s.size();) {
                string tempStr = "";
                int i2 = i;
                for (int j = i; s[j] != 32 && j < s.size(); j++)
                {
                    tempStr += s[j];
                    i2 = j + 2;
                }
                i = i2;
                tempVec.push_back(tempStr);
                if (i2 > s.size())
                    break;
            }
            
	//쪼갠 word를 word옆 숫자의 순서대로 res(string)에 삽입
            string res = "";
            int k = '1';
            while (1) {
                for (int i = 0; i < tempVec.size(); i++) {
                    string tempStr2 = "";
                    for (int j = 0; j < tempVec[i].size(); j++) {
                        tempStr2 += tempVec[i][j];
                        if (tempVec[i][j] == k)
                        {
                            tempStr2.erase(j);
                            res += tempStr2;
                            res += " ";
                        }
                    }
                }

                k++;
                if ((k - 49) == tempVec.size())
                {
                    res.erase(res.size()-1);
                    return res;
                }
            }
        
       
    }
};