[英]What is the Time complexity of this algorithim?
该算法检查 2 个字符串是否同构。 ]
注意:字符串必须具有相同的大小才能同构。
该算法将字符映射到一个 arraylist 代表它们出现的每个索引以检查同构。 我相信空间复杂度是 O(s.length),因为所有列表的组合大小是 strings.size。
时间复杂度是多少? 我知道它是在我们检查列表等效性的最后一个循环中确定的,但我无法确定。
class Solution {
public boolean isIsomorphic(String s, String t) {
if (s.length() != t.length()){
return false;
}
HashMap<Character,ArrayList<Integer>> smap = new HashMap();
HashMap<Character,ArrayList<Integer>> tmap = new HashMap();
for (int i = 0; i < s.length(); i++) {
char schar = s.charAt(i);
char tchar = t.charAt(i);
if (!smap.containsKey(schar)){
smap.put(schar, new ArrayList());
smap.get(schar).add(i);
}
else{
smap.get(schar).add(i);
}
if (!tmap.containsKey(tchar)){
tmap.put(tchar, new ArrayList());
tmap.get(tchar).add(i);
}
else{
tmap.get(tchar).add(i);
}
}
for (int i = 0; i < s.length(); i++){
char schar = s.charAt(i);
char tchar = t.charAt(i);
if (!smap.get(schar).equals(tmap.get(tchar))){
return false;
}
}
return true;
}
}
代码对字符串进行一次迭代 rest 的操作成本为 O(N),因此添加复杂性并忽略系数,代码的整体时间复杂度为 O(N)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.