题目:leetcode 2788
给你一个字符串数组 words 和一个字符 separator ,请你按 separator 拆分 words 中的每个字符串。
返回一个由拆分后的新字符串组成的字符串数组,不包括空字符串 。
注意
输入:words = ["one.two.three","four.five","six"], separator = "."
输出:["one","two","three","four","five","six"]
解释:在本示例中,我们进行下述拆分:
"one.two.three" 拆分为 "one", "two", "three"
"four.five" 拆分为 "four", "five"
"six" 拆分为 "six"
因此,结果数组为 ["one","two","three","four","five","six"] 。
示例 2:
输入:words = ["$easy$","$problem$"], separator = "$"
输出:["easy","problem"]
解释:在本示例中,我们进行下述拆分:
"$easy$" 拆分为 "easy"(不包括空字符串)
"$problem$" 拆分为 "problem"(不包括空字符串)
因此,结果数组为 ["easy","problem"] 。
示例 3:
输入:words = ["|||"], separator = "|"
输出:[]
解释:在本示例中,"|||" 的拆分结果将只包含一些空字符串,所以我们返回一个空数组 [] 。
提示:
分析:
先简单说一下这道题思路:遍历每一个字符串,寻找separator字符,如果找到,就从这个节点到上一个节点的字符串截下来。是不是咋一眼挺好做,其实不然!
难点主要有两个
题解:
class Solution {
public List<String> splitWordsBySeparator(List<String> words, char separator) {
List<String> res = new ArrayList<String>();
for (String word : words) {
StringBuilder sb = new StringBuilder();
int length = word.length();
for (int i = 0; i < length; i++) {
char c = word.charAt(i);
if (c == separator) {
if (sb.length() > 0) {
res.add(sb.toString());
sb.setLength(0);
}
} else {
sb.append(c);
}
}
if (sb.length() > 0) {
res.add(sb.toString());
}
}
return res;
}
}
注意:
class Solution {
public List<String> splitWordsBySeparator(List<String> words, char separator) {
List<String> res = new ArrayList<>();
for (String word : words) {
int pre = 0;
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == separator) {
if(i == 0 || i == word.length()) {
} else if (pre != i ) {
String s = word.substring(pre, i);
res.add(s);
}
pre = i + 1;
}
if (i == word.length() - 1 && word.charAt(i) != separator) {
res.add(word.substring(pre, i) + word.charAt(i));
}
}
}
return res;
}
}