1: class Solution {
2: public:
3: bool isOneEditDistance(string s, string t) {
4: int ns = s.size();
5: int nt = t.size();
6: int n = min(ns, nt);
7: for (int i = 0; i < n; i++) {
8: if (s[i] != t[i]) {
9: if (ns == nt) return s.substr(i+1) == t.substr(i+1); // replace s[i] with t[i]
10: else if (ns < nt) return s.substr(i) == t.substr(i+1); // delete t[i]
11: else return s.substr(i+1) == t.substr(i); // delete s[i]
12: }
13: }
14: return abs(ns-nt) == 1; // one character long otherwise two strings are equal.
15: }
16: };
Wednesday, August 17, 2016
161. One Edit Distance
I was thinking of DP, but it turns out quite straightforward. See the comments in the code.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment