算法:有效的字母异位词
13122256420
676
2024-02-26
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。

输入:a = “abc”  b = "acb"   输出:true

输入:a = “abc”  b = "ecb"   输出:false


js本版

function is_anagram() {
    let a = "ratsat"
    let b = "catsat"
    let c = "atrsat"


    let obj = {}

    for (let i = 0; i < a.length; i++) {
        if (obj[a[i]]) {
            obj[a[i]] += 1
        } else {
            obj[a[i]] = 1
        }
    }
    let bool = true
    for (let i = 0; i < c.length; i++) {
        let r = obj[c[i]]
        if (r) {
            r -= 1
        } else {
            bool = false
            break
        }

        if (r < 0) {
            bool = false
            break
        }
    }
}

go版本

func is_anagram() {
	var a = "ratsat"
	var b = "catsat"
	//var c = "atrsat"

	obj := map[string]int{}
	bools := true

	for i := 0; i < len(a); i++ {
		fmt.Println(string(a[i]))
		var res = string(a[i])
		if _, ok := obj[res]; ok {
			obj[res] = obj[res] + 1
		} else {
			obj[res] = 1
		}
	}
	fmt.Println(obj)

	for i := 0; i < len(b); i++ {
		var res = string(b[i])
		if _, ok := obj[res]; ok {
			obj[res] = obj[res] - 1
		} else {
			bools = false
			break
		}

		if obj[res] < 0 {
			bools = false
			break
		}
	}

	fmt.Println(bools)
}

rust版本

fn is_anagram() {
    let a = "ratsat";
    let b = "catsat";
    let c = "atrsat";

    let mut obj = HashMap::new();
    let mut bools = true;

    for i in a.chars() {
        println!("{}", i);
        let res = obj.entry(i).or_insert(0);
        *res += 1;
    }
    println!("{:?}", obj);

    for i in c.chars() {
        println!("{}", i);
        let res = obj.entry(i).or_insert(0);
        *res -= 1;

        if *res < 0 {
            bools = false;
            break;
        }
    }
    println!("{}", bools)
}