C/C++教程

299. Bulls and Cows [Medium]

本文主要是介绍299. Bulls and Cows [Medium],对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
/**
 * Runtime: 18 ms, faster than 11.23%
 * Memory Usage: 39 MB, less than 67.38%
 */
class Solution {
    public String getHint(String secret, String guess) {
        int a = 0, b = 0;
        char[] sec = secret.toCharArray();
        char[] gue = guess.toCharArray();
        // find all a
        for (int i = 0; i < sec.length; i++) {
            if (sec[i] == gue[i]) {
                a++;
                sec[i] = 'n';
                gue[i] = 'n';
            }
        }
        // find all b
        for (int i = 0; i < sec.length; i++) {
            if (sec[i] != 'n') {
                int idx = guess.indexOf(sec[i]);
                while (idx != -1 && gue[idx] == 'n') {
                    idx = guess.indexOf(sec[i], idx + 1);
                }
                if (idx != -1) {
                    b++;
                    gue[idx] = 'n';
                }    
            }
        }
        // form the result string
        StringBuilder sb = new StringBuilder();
        sb.append(a).append("A").append(b).append("B");
        return sb.toString();
    }
}
这篇关于299. Bulls and Cows [Medium]的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!