- 反转字符串
题目: 编写一个函数来反转一个字符串。
public class Main {
public static String reverseString1(String s) {
return new StringBuilder(s).reverse().toString();
}
public static void main(String[] args) {
String str = "hello";
System.out.println(reverseString(str)); // 输出: "olleh"
}
}
- 判断回文字符串
题目: 编写一个函数来判断给定的字符串是否是回文。
public class Main {
public static boolean isPalindrome(String s) {
int left = 0, right = s.length() - 1;
while (left < right) {
if (s.charAt(left) != s.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
public static void main(String[] args) {
String str = "madam";
System.out.println(isPalindrome(str)); // 输出: true
}
}
- 字符串中的第一个唯一字符
题目: 找到字符串中第一个不重复的字符并返回它的索引。如果不存在,则返回-1。
import java.util.HashMap;
import java.util.Map;
public class Main {
public static int firstUniqChar(String s) {
Map<Character, Integer> count = new HashMap<>();
for (char c : s.toCharArray()) {
count.put(c, count.getOrDefault(c, 0) + 1);
}
for (int i = 0; i < s.length(); i++) {
if (count.get(s.charAt(i)) == 1) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
String str = "loveleetcode";
System.out.println(firstUniqChar(str)); // 输出: 2
}
}
- 字符串中的最长公共前缀
题目: 编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串。
public class Main {
public static String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) return "";
String prefix = strs[0];
for (int i = 1; i < strs.length; i++) {
while (strs[i].indexOf(prefix) != 0) {
prefix = prefix.substring(0, prefix.length() - 1);
if (prefix.isEmpty()) return "";
}
}
return prefix;
}
public static void main(String[] args) {
String[] strs = {"flower", "flow", "flight"};
System.out.println(longestCommonPrefix(strs)); // 输出: "fl"
}
}
65 字符串压缩
题目: 编写一个函数,按如下规则压缩字符串:对字符串中连续出现的每个字符,用该字符和它连续出现的次数表示。若压缩后的字符串长度比原字符串长度更短,则返回压缩后的字符串,否则返回原字符串。
复制代码
public class Main {
public static String compressString(String s) {
StringBuilder sb = new StringBuilder();
int count = 1;
for (int i = 0; i < s.length(); i++) {
if (i + 1 < s.length() && s.charAt(i) == s.charAt(i + 1)) {
count++;
} else {
sb.append(s.charAt(i)).append(count);
count = 1;
}
}
return sb.length() < s.length() ? sb.toString() : s;
}
public static void main(String[] args) {
String str = "aabcccccaaa";
System.out.println(compressString(str)); // 输出: "a2b1c5a3"
}
}