繁体   English   中英

Java检查该字符串是否是另一个字符串O(log n)的字谜

[英]Java check if the string is an anagram of another string O ( log n )

因此,我最近一直在研究与算法的运行时复杂度有关的所有问题,并想学习如何在n的规模增加时进行更改以提高效率,所以本质上我的目标是学习如何制作事物O(日志n)。 对自己想,我知道这个小时我可以做一个很好的小项目,那就是创建一个字谜检查器。

我翻遍了几篇SO帖子,看到有人评论说,如果您将字母表中的每个字母都分配给一个数字,则可以将其设置为log n:

final Map<Character, Integer> map;
        String str = "hello";
        String check = "olleh";

        map = new HashMap<>();
        map.put('a', 2);
        map.put('b', 3);
        map.put('c', 4);
        map.put('d', 7);
        map.put('e', 11);
        map.put('f', 13);
        map.put('g', 17);
        map.put('h', 19);
        map.put('i', 23);
        map.put('j', 29);
        map.put('k', 31);
        map.put('l', 37);
        map.put('m', 41);
        map.put('n', 43);
        map.put('o', 47);
        map.put('p', 53);
        map.put('q', 59);
        map.put('r', 61);
        map.put('s', 67);
        map.put('t', 71);
        map.put('u', 73);
        map.put('v', 79);
        map.put('w', 83);
        map.put('x', 89);
        map.put('y', 97);
        map.put('z', 101);

然后我创建了方法:

 public static boolean isAnagram(String s, String check,Map<Character, Integer> map) {
        int stringTotal = 0;
        int checkTotal = 0;
        for(char ch: s.toCharArray()){
            int i = map.get(ch);
            stringTotal += ch;
        }
        for(char ch: check.toCharArray()){
            int i = map.get(ch);
            checkTotal +=ch;
        }
        if (stringTotal == checkTotal){
            return true;
        }
        return false;
    }

我认为该方法是O(n ^ 2),因为它具有两个独立的循环,我无法想到将其创建为O(log n)方法的逻辑。

任何指针都很棒

看起来是O(2n) :一个n循环。 你会得到O(n^2)如果你循环n的循环中n ,就像这样:

int count = 0;
for ( int x = 0; x < n; x++ )
     for ( int y = 0; y < n; y++ )
         count++;

在这里, count将为n*n或n 2

在您粘贴的代码中,有两个循环:

int count = 0;
for ( int x = 0; x < n; x++ )
    count++;
for ( int y = 0; y < n; y++ )
    count++;

此处, countn+n或2n。

没有办法使O(log n)函数,因为您将始终需要检查所有n值(所有字母)。

例如,让我们说,我们计算出准确的时间复杂度的功能是log(n)注意,这是从订单不同O(log n)与系数和低阶方面确实走)。
现在,如果n = 10 然后log(n) = 2.3 (大约),如果仅查看2.3个字母,就不能确定十个字母的单词是另一个10个字母的单词的字谜。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM