LintCode

      • 两个字符串是变位词
      • 比较字符串

两个字符串是变位词

LintCode_第1张图片

import java.util.Arrays;
public class Solution {
    /**
     * @param s: The first string
     * @param b: The second string
     * @return true or false
     */
    public boolean anagram(String s, String t){
        if (s.length() != t.length()){
            return false;
        }
        char[] news = s.toCharArray();
        char[] newt = t.toCharArray();
        Arrays.sort(news);
        Arrays.sort(newt);
        for (int i = 0; i < news.length; i++){
            if (news[i] != newt[i]){
                return false;
            }
        }
        return true;
    }
};

**注意:碰到类似题目应该询问要不要把空格算成一个char

比较字符串

LintCode_第2张图片

public class Solution {
    /**
     * @param A : A string includes Upper Case letters
     * @param B : A string includes Upper Case letter
     * @return :  if string A contains all of the characters in B return true else return false
     */
    public boolean compareStrings(String A, String B) {
         char[] array_b = B.toCharArray(); 
         Arrays.sort(array_b);
         int count = 0;
            for (char b : array_b) {
                if(A.indexOf(b)!=-1){
                    String sb = Character.toString(b);
                    A = A.replaceFirst(sb, "");
                    count++;
                    }
            }
            if (count == B.length() || B=="") {
                return true;
            }else{
            return false;
            }
        }
}

**注意:碰到类似题目应该询问要不要把空格算成一个char

你可能感兴趣的:(Algorithm,String,lintcode)