不准访问
- 积分
- 108
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2013-12-13
- 最后登录
- 1970-1-1
|
写了下第一题swap string,不知道有没有什么问题
- // Check if two strings can equal after one swap of two chars
- // e.g.
- // conSerVe
- // conVerSe
- // ==> true
- public class Solution {
- // tag: ptr
- // time: O(n)
- // space: O(1)
- public boolean swaqEq (String a, String b) {
- if (a == null || b == null) return false;
- if (a.length() != b.length()) return false;
- char[] A = a.toCharArray();
- char[] B = b.toCharArray();
- int i = 0;
- while (i < A.length && A[i] == B[i]) i++;
- int j = A.length - 1;
- while (j >= 0 && A[j] == B[j]) j--;
- swap(A, i, j);
- for (int k = i; k <= j; k++) {
- if (A[k] != B[k]) return false;
- }
- return true;
- }
- private void swap(char[] A, int i, int j) {
- char tmp = A[i];
- A[i] = A[j];
- A[j] = tmp;
- }
- public static void main(String[] args) {
- System.out.println(new Solution().swaqEq("conSerVe",
- "conVerSe"));
- System.out.println(new Solution().swaqEq("conSeYrVe",
- "conVeXrSe"));
- }
- }
- // follow up: multiple swap
- // e.g.
- // conSSSerBVVe
- // conVVBerSSSe
- // ==> true
- class SolutionII {
- // tag: hash
- // time: O(n)
- // space: O(n)
- public boolean swapEq(String a, String b) {
- if (a == null || b == null) return false;
- if (a.length() != b.length()) return false;
- char[] A = a.toCharArray();
- char[] B = b.toCharArray();
- Map<Character, Map<Character, Integer>> m = new HashMap<>(); // bChar2<aChar2swapNeededCnt>
- int swapNeededCnt = 0;
- for (int i = 0; i < A.length; i++) {
- if (A[i] != B[i]) {
- if (m.containsKey(A[i]) && m.get(A[i]).containsKey(B[i])) {
- m.get(A[i]).put(B[i], m.get(A[i]).get(B[i]) - 1);
- if (m.get(A[i]).get(B[i]) == 0) m.get(A[i]).remove(B[i]);
- swapNeededCnt--;
- continue;
- }
- swapNeededCnt++;
- m.putIfAbsent(B[i], new HashMap<>());
- m.get(B[i]).put(A[i], m.get(B[i]).getOrDefault(A[i], 0) + 1);
- }
- }
- return swapNeededCnt == 0;
- }
- public static void main(String[] args) {
- System.out.println(new SolutionII().swapEq("conSSSerBVVe",
- "conVVBerSSSe"));
- System.out.println(new SolutionII().swapEq("conSSSerBVVe",
- "conXVBerSSSe"));
- }
- }
复制代码 |
|