-
Notifications
You must be signed in to change notification settings - Fork 33
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
This is a C++ file that consists of solution to LC POTD of 6-10-2024 [813. Sentence Similarity III]
- Loading branch information
1 parent
4a83fac
commit 2aecff5
Showing
1 changed file
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
class Solution { | ||
private: | ||
vector<string> convert(string sentence){ | ||
sentence += " "; | ||
vector<string> ans; | ||
|
||
string word = ""; | ||
for(int i=0;i<sentence.size();i++){ | ||
if(sentence[i]==' '){ | ||
ans.push_back(word); | ||
word=""; | ||
} | ||
else{ | ||
word += sentence[i]; | ||
} | ||
} | ||
|
||
return ans; | ||
} | ||
public: | ||
bool areSentencesSimilar(string x, string y) { | ||
// we want x to always be longest to avoid else-if conditions | ||
if (x.length() < y.length()) { | ||
swap(x, y); | ||
} | ||
|
||
// first store the words from sentences | ||
vector<string> vx, vy; | ||
vx = convert(x); | ||
vy = convert(y); | ||
|
||
int l = 0; | ||
// we will try to match words from prefix part | ||
for(int i = 0; i < vy.size(); i++) { | ||
if(vx[i] == vy[i]) { | ||
l++; | ||
} | ||
else { | ||
break; | ||
} | ||
} | ||
|
||
int ind = vx.size() - 1, r=vy.size(); | ||
// we will try to match words from suffix part | ||
for(int i=vy.size()-1; i>=0; i--){ | ||
if(vy[i] == vx[ind]){ | ||
ind--; | ||
r=i; | ||
} | ||
else{ | ||
break; | ||
} | ||
} | ||
|
||
// if they overlaps | ||
return r <= l; | ||
} | ||
}; |