-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuddystring.java
More file actions
88 lines (73 loc) · 2.12 KB
/
Copy pathBuddystring.java
File metadata and controls
88 lines (73 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*859. Buddy Strings
Solved
Easy
Topics
premium lock icon
Companies
Given two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false.
Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j].
For example, swapping at indices 0 and 2 in "abcd" results in "cbad".
Example 1:
Input: s = "ab", goal = "ba"
Output: true
Explanation: You can swap s[0] = 'a' and s[1] = 'b' to get "ba", which is equal to goal.
Example 2:
Input: s = "ab", goal = "ab"
Output: false
Explanation: The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in "ba" != goal.
Example 3:
Input: s = "aa", goal = "aa"
Output: true
Explanation: You can swap s[0] = 'a' and s[1] = 'a' to get "aa", which is equal to goal.
Constraints:
1 <= s.length, goal.length <= 2 * 104
s and goal consist of lowercase letters. */
class Solution {
public boolean buddyStrings(String s, String goal) {
//PART 1
if(s.length()!=goal.length())
{
return false;
}
// PART2
if(s.equals(goal))
{
HashMap <Character,Integer> map=new HashMap<>();
for(int i=0;i<s.length();i++)
{
map.put(s.charAt(i),map.getOrDefault(s.charAt(i),0)+1);
if(map.get(s.charAt(i)) >= 2)
{
return true;
}
}
return false;
}
//PART 3
int first=-1;
int second=-1;
int count=0;
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)!=goal.charAt(i))
{
count++;
if(first==-1)
{
first=i;
}
else
{
second=i;
}
}
}
if(count!=2)
{
return false;
}
return s.charAt(first) == goal.charAt(second) &&s.charAt(second) == goal.charAt(first);
}
}
//tc=o(n)
//sc=o(n)