Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Thử Thách Đảo Ngược Chuỗi (Reverse String) Trong JavaScript

Một trong những thách thức thuật toán/mã đầu tiên chúng ta giải quyết như kỹ sư phần mềm và nhà phát triển web mới là tìm ra cách đảo ngược chuỗi. Nhớ rằng chuỗi chỉ là tập hợp ký tự và khoảng trắng. Điều cần làm là thử đảo ngược, ví dụ, chuỗi "Hello World!" và trả về "!dlroW olleH". Có vài cách giải quyết vấn đề này và chúng ta sẽ trình bày một số cách ở đây.

Đề Bài

Viết hàm reverseString đảo ngược chuỗi và trả về nó. Chuỗi cần đảo ngược được đưa làm đối số trong hàm.

Giải Pháp #1: Vòng Lặp For

Giải pháp đầu tiên, và có lẽ đơn giản nhất, là dùng vòng lặp for và duyệt ngược qua chuỗi. Cần khởi tạo biến chứa chuỗi đảo ngược mới khi duyệt qua từng ký tự:

function reverseString(str) { 
    let newStr = ''; 
    for(let i = str.length - 1; i >= 0; i--) { 
        newStr += str[i]; 
    } 
    return newStr; 
}

Gán i cho chỉ mục cuối (tính bằng cách trừ 1 từ độ dài chuỗi) ⇒ đây là khởi tạo và phục vụ như chỉ mục đầu tiên lặp qua. Phần thứ hai của vòng lặp for là điều kiện ⇒ nói cho vòng lặp biết khi nào dừng. Phần ba và cuối là i sẽ tăng/giảm bao nhiêu sau khi hoàn thành vòng lặp và điều kiện vẫn đúng: i– về cơ bản lấy i và gán lại thành i – 1.

Khi lặp qua mỗi lần, lấy ký tự tại str[i] và thêm vào newStr. Sau đó trả về newStr bên ngoài vòng lặp và kết thúc hàm.

Thử ngay trong trình soạn thảo mã:

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8" /> 
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> 
<title></title> 
<meta name="description" content="" /> 
<meta name="viewport" content="width=device-width, initial-scale=1" /> 
<link rel="stylesheet" href="" /> 
<script> 
function reverseString(str) { 
    let newStr = ''; 
    for(let i = str.length - 1; i >= 0; i--) { 
        newStr += str[i]; 
    } 
    return newStr; 
} 
function showInput(e) { 
    e.preventDefault(); 
    const inputStr = document.getElementById('user_input').value; 
    if(inputStr.length < 1) { 
        alert("Must enter a string to reverse. Try again.") 
    } 
    let reversed = reverseString(inputStr); 
    document.getElementById( 'display' ).innerHTML = reversed; 
    document.getElementById('user_input').value = ''; 
} 
</script> 
<style> 
* { box-sizing: border-box;; } 
body { width: 100%; max-width: 500px; height: 100vh; background: lightblue; margin: 0 auto; display: flex; flex-flow: column wrap; align-items: center; justify-content: center; } 
div { display: flex; flex-flow: column wrap; align-items: flex-start; width: 100%; } 
form { display: flex; flex-flow: column wrap; width: 100%; background: lightgray; padding: 20px; border: 5px double slategray; } 
#user_input { width: 100%; } 
#submit_button { width: 25%; align-self: flex-end; margin-top: 10px; } 
#display { font-size: 1.4rem; height: 50px; } 
</style> 
</head> 
<body> 
<div> 
<form onsubmit="showInput(event);"> 
<label id="label">Enter a String to Reverse:</label> 
<input type="text" name="message" id="user_input"/> 
<input type="submit" onclick="showInput(event);" id="submit_button"/><br /> 
<label>Your input: </label> 
<p><span id="display"></span></p> 
</form> 
</div> 
</body> 
</html>

Giải Pháp #2: Phương Thức map ES6 Của JavaScript

JavaScript có phương thức mảng tích hợp sẵn mới trong ES6 gọi là map. Phương thức này trả về mảng mới với các giá trị được chỉ định. Phương thức map có ba tham số: mục hiện tại, chỉ mục của mục, và bản sao mảng nó đến từ. Chúng ta sẽ dùng hai tham số cuối.

Điều đầu tiên cần làm là tách chuỗi thành mảng dùng phương thức split(). Nếu tách trên chuỗi rỗng, phương thức cho mảng với từng ký tự riêng lẻ. Sau đó dùng mảng mới đó để map qua.

function reverseString(str) { 
    let newArr = str.split(''); 
    let rev = newArr.map((letter, index, array) => { 
        let swapIndex = array.length - index - 1; 
        return array[swapIndex]; 
    }); 
    return rev.join('') 
}

Vì muốn hoán đổi chỉ mục, cần tìm chỉ mục ký tự muốn đặt vào vị trí chỉ mục hiện tại. Đó sẽ là ký tự trả về.

Để làm điều đó, tìm độ dài mảng, trừ một vì mảng dựa trên chỉ mục 0, rồi trừ vị trí chỉ mục hiện tại. array[swapIndex] trả về về cơ bản lấy vị trí của chỉ mục hiện tại. Điều này cho mảng các ký tự đảo ngược trong chuỗi.

Điều cuối cùng cần làm là nối mảng lại thành chuỗi và trả về.

Thử giải pháp trong trình soạn thảo mã!

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8" /> 
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> 
<title></title> 
<meta name="description" content="" /> 
<meta name="viewport" content="width=device-width, initial-scale=1" /> 
<link rel="stylesheet" href="" /> 
<script> 
function reverseString(str) { 
    let newArr = str.split(''); 
    let rev = newArr.map((letter, index, array) => { 
        let newIndex = array.length - index - 1; 
        return array[newIndex]; 
    }); 
    return rev.join('') 
} 
function showInput(e) { 
    e.preventDefault(); 
    const inputStr = document.getElementById('user_input').value; 
    if(inputStr.length < 1) { 
        alert("Must enter a string to reverse. Try again.") 
    } 
    let reversed = reverseString(inputStr); 
    document.getElementById( 'display' ).innerHTML = reversed; 
    document.getElementById('user_input').value = ''; 
} 
</script> 
<style> 
* { box-sizing: border-box;; } 
body { width: 100%; max-width: 500px; height: 100vh; background: lightblue; margin: 0 auto; display: flex; flex-flow: column wrap; align-items: center; justify-content: center; } 
div { display: flex; flex-flow: column wrap; align-items: flex-start; width: 100%; } 
form { display: flex; flex-flow: column wrap; width: 100%; background: lightgray; padding: 20px; border: 5px double slategray; } 
#user_input { width: 100%; } 
#submit_button { width: 25%; align-self: flex-end; margin-top: 10px; } 
#display { font-size: 1.4rem; height: 50px; } 
</style> 
</head> 
<body> 
<div> 
<form onsubmit="showInput(event);"> 
<label id="label">Enter a String to Reverse:</label> 
<input type="text" name="message" id="user_input"/> 
<input type="submit" onclick="showInput(event);" id="submit_button"/><br /> 
<label>Your input: </label> 
<p><span id="display"></span></p> 
</form> 
</div> 
</body> 
</html>

Điều quan trọng nhớ là map trả về mảng mới – nên không sửa đổi str/mảng gốc truyền vào.

Giải Pháp #3: Phương Thức Tích Hợp JavaScript

Phương pháp giải thử thách này dùng các hàm/phương thức tích hợp split(), reverse(), và join() giải quyết trong một dòng:

function reverseString(str) { 
    return str.split('').reverse().join(''); 
}

Thử chạy mã dưới và test để thấy nó hoạt động!

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8" /> 
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> 
<title></title> 
<meta name="description" content="" /> 
<meta name="viewport" content="width=device-width, initial-scale=1" /> 
<link rel="stylesheet" href="" /> 
<script> 
function reverseString(str) { 
    return str.split('').reverse().join(''); 
} 
function showInput(e) { 
    e.preventDefault(); 
    const inputStr = document.getElementById('user_input').value; 
    if(inputStr.length < 1) { 
        alert("Must enter a string to reverse. Try again.") 
    } 
    let reversed = reverseString(inputStr); 
    document.getElementById( 'display' ).innerHTML = reversed; 
    document.getElementById('user_input').value = ''; 
} 
</script> 
<style> 
* { box-sizing: border-box;; } 
body { width: 100%; max-width: 500px; height: 100vh; background: lightblue; margin: 0 auto; display: flex; flex-flow: column wrap; align-items: center; justify-content: center; } 
div { display: flex; flex-flow: column wrap; align-items: flex-start; width: 100%; } 
form { display: flex; flex-flow: column wrap; width: 100%; background: lightgray; padding: 20px; border: 5px double slategray; } 
#user_input { width: 100%; } 
#submit_button { width: 25%; align-self: flex-end; margin-top: 10px; } 
#display { font-size: 1.4rem; height: 50px; } 
</style> 
</head> 
<body> 
<div> 
<form onsubmit="showInput(event);"> 
<label id="label">Enter a String to Reverse:</label> 
<input type="text" name="message" id="user_input"/> 
<input type="submit" onclick="showInput(event);" id="submit_button"/><br /> 
<label>Your input: </label> 
<p><span id="display"></span></p> 
</form> 
</div> 
</body> 
</html>

Về cơ bản, phương thức reverse() tích hợp làm những gì phương thức map() (giải pháp trước) làm dưới lớp; tuy nhiên, nó biến đổi mảng gốc thay vì trả về mảng mới vì nó đảo ngược ngay tại chỗ (in place). Nếu giải quyết vấn đề lớn hơn, bạn có thể cần tạo bản sao mảng gốc để vẫn truy cập được bản gốc nếu cần.

Đây không phải cách giải quyết duy nhất – chỉ là một số cách phổ biến hơn. Hãy thử nghiệm và xem bạn có thể tìm giải pháp khác cho riêng mình trong trình soạn thảo mã. Chỉ chỉnh sửa hàm reverseString() và không chỉnh sửa gì khác nếu muốn thấy trên màn hình.