LintCode(158)

两个字符串是变位词
写出一个函数 anagram(s, t) 去判断两个字符串是否是颠倒字母顺序构成的
样例
给出 s="abcd"t="dcba",返回ture

未采用数据结构的写法:

public class Solution {
    /**
     * @param s: The first string
     * @param t: The second string
     * @return true or false
     */
    public boolean anagram(String s, String t) {
        // write your code here
        int a = s.length();
        int b = t.length();
        if (a != b){
            return false;
        }
        for (int i = 0; i < a; i++){
            char m = s.charAt(i);
            int num = 0; //标记值
            for (int j = 0; j < a; j++){
                if (t.charAt(j) == m){
                    num = 1;
                }
            }
            if (num == 1){
                continue;
            } else {
                return false;
            }
        }
        return true;
    }
};

此种解法实际是有错误的,比如"abbb","baaa"会被误认为是变位词,实际未然。

利用hash表对字符串存储,可得到理想的结果。代码如下:

import java.util.*;
public class test{    
public boolean compareStrings(String A, String B) {
    test cs = new test();
    if(B.length() > A.length())
        return false;
    Map<Character,Integer> aMap = cs.StringToMap(A);
    for(int i = 0; i < B.length(); i++){
        char b = B.charAt(i);
        if (aMap.containsKey(b)){
            if(aMap.get(b) > 1){
                int times = aMap.get(b)-1;
                aMap.put(b, times);
            }else
                aMap.remove(b);
            }else
                return false;
    }
    return true;
}

public Map<Character,Integer> StringToMap(String S){
    Map<Character,Integer> sMap = new HashMap<Character,Integer>();
    for(int i = 0; i < S.length();i++){
        char a = S.charAt(i);
        if(sMap.containsKey(a)){
            int times = sMap.get(a)+1;
            sMap.put(a, times);
        }else
            sMap.put(a, 1);
    }
    return sMap;
}

public static void main(String []args){
    test cst = new test();
    boolean c = cst.compareStrings("aaadbb", "dbaaba");
    System.out.print(c);
}
}

函数StringToMap 完成的功能是将字符串存储在hash表中,且返回一个对应的map映射。
比如StringToMap("lint"),返回的map<Character,Integer> 映射为{t=1, n=1, l=1, i=1}
StringToMap("aaadbb") 返回的map 映射为{d=1,b=2,a=3};
(不过此处put函数为何按照字母从大到小放入到map中呢?不解)
compareStrings()的思路其实同StringToMap() 函数。

算法复杂度是O(n) 吧。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值