替换空格
cpp
class Solution {
public:
string replaceSpace(string s) {
string res ;
for(int i = 0; s[i]; i++) {
if(s[i] != ' ') res += s[i];
else res += "%20";
}
return res;
}
};
java
class Solution {
public String replaceSpace(String s) {
String res = "";
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) != ' ') res += s.charAt(i);
else res += "%20";
}
return res;
}
}
优化:
class Solution {
public String replaceSpace(String s) {
StringBuilder res = new StringBuilder();
for(Character c : s.toCharArray())
{
if(c == ' ') res.append("%20");
else res.append(c);
}
return res.toString();
}
}
颠倒字符串中的单词
双端队列(cpp)
class Solution {
public:
string reverseWords(string s) {
string res;
int l = s.size()-1,r = s.size()-1;
while(l >=0) {
if(l == 0) {
res += s.substr(l,r);
}
if(s[l] != ' ')l--;
else {
if(l != 0) {
res += s.substr(l, r);
res += ' ';
} else res += s.substr(l, r);
l --;
r = l;
}
}
return res;
}
};
双指针(java)
class Solution {
public String reverseWords(String s) {
char[] result = new char[s.length()];
char[] arr = s.toCharArray();
// currIdx:result当前位置,left:单词首字符位置,right:单词尾字符位置
int currIdx = 0, left = s.length() - 1, right = left;
for (; left >= 0; left--) {
// 首字符是' ' 且 首尾字符位置不相等,则认为一个单词逆序遍历结束,应当放到结果集
if (arr[left] == ' ' && left != right) {
int len = right - left;
// 首字符是' ',不能放入结果集,从left+1开始放
System.arraycopy(arr, left + 1, result, currIdx, len);
currIdx += len;
right = left;
// 单词尾部添加' '
result[currIdx++] = ' ';
}
// 尾字符是' ',不能放入结果集
if (arr[right] == ' ') {
right--;
}
}
// 尾字符位置>=0,表示还有单词未放入结果集
if (right >= 0) {
System.arraycopy(arr, 0, result, currIdx, right + 1);
}
return new String(result).trim();
}
}
左旋转字符串
java
class Solution {
public String reverseLeftWords(String s, int n) {
StringBuffer res = new StringBuffer();
for(int i = n; i < s.length(); i++)
res.append(s.charAt(i));
for(int i = 0; i < n; i ++)
res.append(s.charAt(i));
return res.toString();
}
}
c++
class Solution {
public:
string reverseLeftWords(string s, int n) {
reverse(s.begin(), s.begin() + n);
reverse(s.begin() + n, s.end());
reverse(s.begin(), s.end());
return s;
}
};