|
|
|
---
|
|
|
|
字符串相关
|
|
|
|
---
|
|
|
|
|
|
|
|
[05. 替换空格](https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/)
|
|
|
|
|
|
|
|
```java
|
|
|
|
class Solution {
|
|
|
|
|
|
|
|
public String replaceSpace(String s) {
|
|
|
|
StringBuilder builder = new StringBuilder();
|
|
|
|
int i = 0;
|
|
|
|
while (i < s.length()) {
|
|
|
|
char c = s.charAt(i);
|
|
|
|
if (c == ' ') {
|
|
|
|
builder.append("%20");
|
|
|
|
} else {
|
|
|
|
builder.append(c);
|
|
|
|
}
|
|
|
|
i++;
|
|
|
|
}
|
|
|
|
return builder.toString();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
[50. 第一个只出现一次的字符](https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof/)
|
|
|
|
|
|
|
|
```java
|
|
|
|
class Solution {
|
|
|
|
public char firstUniqChar(String s) {
|
|
|
|
if (s.length() == 0) {
|
|
|
|
return ' ';
|
|
|
|
}
|
|
|
|
LinkedHashMap<Character, Integer> map = new LinkedHashMap<>();
|
|
|
|
for (char c : s.toCharArray()) {
|
|
|
|
map.put(c, map.getOrDefault(c, 0) + 1);
|
|
|
|
}
|
|
|
|
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
|
|
|
|
if (entry.getValue() == 1) {
|
|
|
|
return entry.getKey();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return ' ';
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
```java
|
|
|
|
class Solution {
|
|
|
|
public char firstUniqChar(String s) {
|
|
|
|
char[] array = s.toCharArray();
|
|
|
|
int[] ints = new int[256];
|
|
|
|
for (char c : array) {
|
|
|
|
ints[c]++;
|
|
|
|
}
|
|
|
|
for (char c : array) {
|
|
|
|
if (ints[c] == 1) {
|
|
|
|
return c;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return ' ';
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
[58 - II. 左旋转字符串](https://leetcode-cn.com/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof/)
|
|
|
|
|
|
|
|
```java
|
|
|
|
class Solution {
|
|
|
|
public String reverseLeftWords(String s, int n) {
|
|
|
|
return s.substring(n) + s.substring(0, n);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
[Offer 58 - I. 翻转单词顺序](https://leetcode-cn.com/problems/fan-zhuan-dan-ci-shun-xu-lcof/)
|
|
|
|
|
|
|
|
```java
|
|
|
|
class Solution {
|
|
|
|
|
|
|
|
public String reverseWords(String s) {
|
|
|
|
String[] strings = s.trim().split(" ");
|
|
|
|
StringBuilder sb = new StringBuilder();
|
|
|
|
for (int i = strings.length - 1; i >= 0; i--) {
|
|
|
|
if (strings[i].equals("")) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
sb.append(strings[i]).append(" ");
|
|
|
|
}
|
|
|
|
return sb.toString().trim();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|