Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Checking smooth sentences in JavaScript
We are required to write a JavaScript function that checks whether a sentence is smooth or not. A sentence is smooth when the first letter of each word in the sentence is same as the last letter of its preceding word.
How It Works
A smooth sentence follows this pattern: if word A ends with letter 'x', then word B must start with letter 'x'. For example, "this stringt tries" is smooth because "this" ends with 's' and "stringt" starts with 's', "stringt" ends with 't' and "tries" starts with 't'.
Example
Following is the code ?
const str = 'this stringt tries sto obe esmooth';
const str2 = 'this string is not smooth';
const isSmooth = str => {
const strArr = str.split(' ');
for(let i = 0; i
Output
Following is the output in the console ?
true
false
Step-by-Step Breakdown
Let's trace through the algorithm with a clearer example:
const checkSmooth = (sentence) => {
console.log(`Checking: "${sentence}"`);
const words = sentence.split(' ');
for(let i = 0; i
Checking: "cat talks"
"cat" ends with "t", "talks" starts with "t"
Smooth sentence!
---
Checking: "cat dog"
"cat" ends with "t", "dog" starts with "d"
Not smooth!
Simplified Version
Here's a more readable version of the same function:
const isSmoothSentence = (sentence) => {
const words = sentence.split(' ');
for(let i = 0; i
true
false
true
Key Points
- Split the sentence into individual words using
split(' ') - Compare the last character of each word with the first character of the next word
- A single word is considered smooth by default
- Return
falseimmediately when a mismatch is found
Conclusion
The smooth sentence checker iterates through word pairs, comparing the last character of one word with the first character of the next. This creates a chain-like pattern where words must connect smoothly.
