leetcode 839 相似字串組

2021-10-18 16:04:13 字數 1039 閱讀 4383

題目在這

困難題看似很複雜,想一想就是圖求連通個數

一眼就是dfs,第二眼是並查集

dfs直接擊敗100%,嚇到了

class

solution

}return res;

}private

void

dfs(string[

]strs,

int i,

boolean

visited)}}

private

boolean

isvalid

(string a,string b)

return

true;}

}

並查集

class

solution

}return ufs.size;

}private

boolean

isvalid

(string a,string b)

return

true;}

}class

unionfindset

}public

intfind

(int x)

while

(father[x]

!=root)

return root;

}public

void

union

(int x,

int y)

else

size--;}

}}

吐個槽,一開始我的isvalid()函式是這麼寫的:

private

boolean

isvalid

(string a,string b)

return

true

;}

僅僅是將字串轉換為陣列,效率差了很多…改天研究一下,因為我之前某道題轉換為陣列明明比字串處理要快的多

要找實習了,收收心看書了

LeetCode 839 相似字串組

如果我們交換字串 x 中的兩個不同位置的字母,使得它和字串 y 相等,那麼稱 x 和 y 兩個字串相似。例如,tars 和 rats 是相似的 交換 0 與 2 的位置 rats 和 arts 也是相似的,但是 star 不與 tars rats 或 arts 相似。總之,它們通過相似性形成了兩個關...

leetCode 839 相似字串組

由題目可知,只要兩個字串相似則它們屬於同乙個連通分量,可以通過並查集維護連通分量的個數,最後返回。class solution return uf.getcount class unionfind public intfind int x return x public boolean union ...

leetcode 839 相似字串組

題意為 找到能交換兩個字元或者相同的就在一組,如果一堆中只有乙個符合這樣的條件就在這個堆中,即ab滿足條件 bc滿足條件那麼abc就在一堆中。並查集,先查詢 再合併到乙個堆中。這裡學習到乙個點就是標記的時候都可以用數字標記,只要符合條件即可,用什麼標記都行。還有題目中給出的是字母異位詞,即只是字母順...