比较字符串

比较两个字符串A和B,确定A中是否包含B中所有的字符。字符串A和B中的字符都是 大写字母

 注意事项

在 A 中出现的 B 字符串里的字符不需要连续或者有序。

样例

给出 A = "ABCD" B = "ACD",返回 true

给出 A = "ABCD" B = "AABC", 返 回 false

 思路:题目的意思就是B中的字符要全部出现在A中,并且例如第二个样例中A在B中有两次,在A中也必须出现两次才算是全部出现在B中。所以就采用将字符串转化为字符数组方便通过下标索引来比较字符。

代码如下:

 public boolean compareStrings(String A, String B) {
        // write your code here
        if(B.isEmpty()) {
			return true;
		}
		int count = 0;
		char[] a = A.toCharArray();
        char[] b = B.toCharArray();
		for(int i=0;i<b.length;i++) {
			for(int j=0;j<a.length;j++) {
				if(b[i]==a[j]) {
					count++;
					a[j]=' ';
					break;
				}
			}
		}if(count==B.length()) {
			return true;
		}
		else {return false;}
    }

猜你喜欢

转载自blog.csdn.net/javaisnotgood/article/details/80369426