Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ff974ad

Browse files
Add solution for One Edit Distance
1 parent 14b96a5 commit ff974ad

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ Algorithm exercises from LeetCode implemented in Java v11.
77
- Sorting Sentence | [Problem](https://leetcode.com/problems/sorting-the-sentence) | [Solution](src/solutions/SortingSentence.java)
88
- Student Attendance Record I | [Problem](https://leetcode.com/problems/student-attendance-record-i) | [Solution](src/solutions/StudentAttendanceRecord.java)
99
- Reverse Words in a String III | [Problem](https://leetcode.com/problems/reverse-words-in-a-string-iii) | [Solution](src/solutions/ReverseWordsInStringIII.java)
10+
- One Edit Distance | [Problem](https://leetcode.com/problems/one-edit-distance) | [Solution](src/solutions/OneEditDistance.java)
1011

1112
### Array
1213
- Jewels and Stones | [Problem](https://leetcode.com/problems/jewels-and-stones) | [Solution](src/solutions/JewelsAndStones.java)

‎src/solutions/OneEditDistance.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package solutions;
2+
3+
// [Problem] https://leetcode.com/problems/one-edit-distance
4+
class OneEditDistance {
5+
// String
6+
// O(n) time, O(n) space
7+
public boolean isOneEditDistance(String s, String t) {
8+
int sLength = s.length(), tLength = t.length();
9+
for (int i = 0; i < Math.min(sLength, tLength); i++) {
10+
if (s.charAt(i) != t.charAt(i)) {
11+
if (sLength < tLength) {
12+
return s.substring(i).equals(t.substring(i + 1));
13+
} else if (sLength > tLength) {
14+
return s.substring(i + 1).equals(t.substring(i));
15+
} else {
16+
return s.substring(i + 1).equals(t.substring(i + 1));
17+
}
18+
}
19+
}
20+
return Math.abs(sLength - tLength) == 1;
21+
}
22+
23+
// Test
24+
public static void main(String[] args) {
25+
OneEditDistance solution = new OneEditDistance();
26+
27+
boolean output1 = solution.isOneEditDistance("ab", "acb");
28+
System.out.println("Test 1 passed? " + (output1 == true));
29+
30+
boolean output2 = solution.isOneEditDistance("", "");
31+
System.out.println("Test 2 passed? " + (output2 == false));
32+
}
33+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /