问题链接
Find the Difference | LeetCode OJ
问题描述
给出两个字符串s和t,这两个字符串仅包含小写字母,字符串t是由字符串s的字符随机排序外加一个额外的字符得到的。请找到那个额外的字符,例如
输入:
s = "abcd"
t = "abcde"
输出:
e
解释:
额外的字符是'e'。
解决办法
以下为我的解决方法,语言为Java
public class Solution {
public char findTheDifference(String s, String t) {
boolean stop = false;
int cursor = 0;
String a = null;
while(!stop){
a = t.substring(cursor,cursor+1);
if(cursor < (t.length() - 1)){
int position = s.indexOf(a);
if(position >= 0){
s = remove(s,position);
cursor ++;
}
else{
stop = true;
}
}
else{
stop = true;
}
}
return a.charAt(0);
}
public String remove(String s,int position){
int originalLength = s.length();
if (position == 0){
s = s.substring(1);
}
else if(position == originalLength){
s = s.substring(0,position);
}
else{
s = s.substring(0,position)+s.substring(position+1,originalLength);
}
return s;
}
}