题解 | #找到字符串中的异位词#
找到字符串中的异位词
http://www.nowcoder.com/practice/9ff491c910e5427fab6ae67745929085
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @param p string字符串
* @return int整型ArrayList
*/
public ArrayList<Integer> findWord (String s, String p) {
// write code here
ArrayList<Integer> res = new ArrayList<>();
p = sort(p);
int lenS = s.length();
int lenP = p.length();
for (int i = 0; i <= lenS - lenP; i++) {
String tmp = s.substring(i, i + lenP);
tmp = sort(tmp);
if (tmp.equals(p)) {
res.add(i);
}
}
return res;
}
public String sort(String p) {
char[] chrs = p.toCharArray();
Arrays.sort(chrs);
StringBuffer sb = new StringBuffer("");
for (char chr : chrs) {
sb.append(chr);
}
return new String(sb);
}
}