1、第一个只出现一次的字符
public class First {
public static void main(String[] args) {
String s = "acscxa";
int ret =First.first(s);
System.out.println(ret);
}
public static int first(String s){
int[] count =new int[125];
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
count[ch]++;
}
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if(count[ch] == 1){
return i;
}
}
return -1;
}
}
优化后的代码如下:
public class First {
public static void main(String[] args) {
String s = "acscxa";
int ret =First.first(s);
System.out.println(ret);
}
public static int first(String s){
int[] count =new int[26];
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
count[ch - 'a']++;//让下标每次从0开始
}
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if(count[ch - 'a'] == 1){
return i;
}
}
return -1;
}
}
2、最后一个字符串的长度
第一种方法:
public class Last {
public static void main(String[] args) {
//这个字符串可以自己写
String s = "this cat is like a beautiful princess";
int index = s.lastIndexOf(" ");
String ret = s.substring(index+1);
int str = ret.length();
System.out.println(str);
}
}
第二种方法:
public static void main(String[] args) {
//输入字符串
Scanner s = new Scanner(System.in);
System.out.println("请输入字符串,以空格分开 :");
String str = s.nextLine();
int index = str.lastIndexOf(" ");//找到最后一个空格
String ret = str.substring(index+1);//截取最后一个字符串
int len = ret.length();//求最后一个字符串的长度
System.out.println(len);//输出最后一个字符串的长度
}
3、检测字符串是否是回文字符串
import java.util.Locale;
public class Repeat {
public static boolean isValidChar(char ch){
if((ch > 'a' && ch < 'z') || (ch > '0' && ch < '9')){
return true;
}
return false;
}
public static boolean repeat(String s) {
String str = s.toLowerCase();
System.out.println(str);//看一下大写字母转小写字母成功了吗
int left = 0;
int right = str.length() - 1;
while (left < right) {
while (left < right) {
left++;
}
while (left < right && isValidChar(s.charAt(right))) {
right--;
}
if (str.charAt(left) == str.charAt(right)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
String s = "BCDEDCB";
System.out.println(s);//输出看一下大写字母
boolean ret =Repeat.repeat(s);
System.out.println(ret);//输出字符串是不是回文的
}
}
另外一种方法:
没有什么大的改变!!!
import java.util.Locale;
public class Repeat {
private static boolean isValidChar(char ch) {
if(Character.isDigit(ch) || Character.isLetter(ch)) {
return true;
}
return false;
}
public static boolean repeat(String s) {
String str = s.toLowerCase();
System.out.println(str);//看一下大写字母转小写字母成功了吗
int left = 0;
int right = str.length() - 1;
while (left < right) {
while (left < right) {
left++;
}
while (left < right && isValidChar(s.charAt(right))) {
right--;
}
if (str.charAt(left) == str.charAt(right)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
String s = "BCDEDCB";
System.out.println(s);//输出看一下大写字母
boolean ret =Repeat.repeat(s);
System.out.println(ret);//输出字符串是不是回文的
}
}