ปัญหา
รับสตริงพิมพ์เล็ก กลับลำดับพยัญชนะ (consonants) ส่วนสระ (vowels) คงตำแหน่งเดิม
ตัวอย่าง
const str = 'somestring';
พยัญชนะ: s,m,s,t,r,n,g → กลับ: g,n,r,t,s,m,s → วางคืนตำแหน่งเดิม → 'gomenrtiss'
โค้ดตัวอย่าง (Two Pointers)
const str = 'somestring';
const reverseConsonants = (str = '') => {
const arr = str.split("");
let i = 0, j = arr.length - 1;
const consonants = 'bcdfghjklnpqrstvwxyz';
while(i < j){
while(i < j && consonants.indexOf(arr[i]) < 0) { i++; }
while(i < j && consonants.indexOf(arr[j]) < 0) { j--; }
let tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp;
i++; j--;
}
return arr.join("");
};
console.log(reverseConsonants(str));
ผลลัพธ์
gomenrtiss