สมมติว่าเรามีประโยคที่: ตัวแรกเป็นพิมพ์ใหญ่ คั่นด้วยช่องว่างเดี่ยว เราต้องจัดเรียงคำตามความยาวเพิ่มขึ้น ถ้าความยาวเท่ากัน รักษาลำดับเดิม
ตัวอย่าง: "I love to code in cpp" → "I to in cpp love code"
วิธีแก้ปัญหา
- แปลงตัวแรกเป็นพิมพ์เล็ก
- แยกคำด้วย space ใส่ vector พร้อม index เดิม
- เรียงตาม (ความยาว, index)
- รวมคำกลับเป็นสตริง ตัวแรกพิมพ์ใหญ่
ตัวอย่างโค้ด C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<string> split(string& s, char delimiter){
vector<string> tokens;
string token;
istringstream tokenStream(s);
while(getline(tokenStream, token, delimiter))
tokens.push_back(token);
return tokens;
}
static bool cmp(pair<string, int>& a, pair<string, int>& b){
if(a.first.size() != b.first.size())
return a.first.size() < b.first.size();
return a.second < b.second;
}
string arrangeWords(string text) {
text[0] += 'a' - 'A';
vector<string> x = split(text, ' ');
vector<pair<string, int>> s;
for (int i = 0; i < x.size(); i++)
s.push_back({ x[i], i });
sort(s.begin(), s.end(), cmp);
string ret = "";
for (int i = 0; i < s.size(); i++) {
ret += s[i].first;
if (i != s.size() - 1) ret += ' ';
}
ret[0] += 'A' - 'a';
return ret;
}
};
int main(){
Solution ob;
cout << (ob.arrangeWords("I love to code in cpp"));
}ข้อมูลนำเข้า
"I love to code in cpp"
ผลลัพธ์
I to in cpp love code