反转字符串
class Solution {
public void reverseString(char[] s) {
int lens=s.length;
int right,left;
if(lens%2!=0)//奇数个
{
right=lens/2+1;
left=lens/2-1;
}
else
{
right=lens/2;
left=lens/2-1;
}
int i=0,j=lens-1;
while(i<=left&&j<=lens-1)
{
char temp=s[i];
s[i]=s[j];
s[j]=temp;
i++;
j--;
}
}
}
反转字符串II
class Solution {
public String reverseStr(String s, int k) {
int len=s.length();
char[] c=s.toCharArray();
for(int i=0;i<len;i+=2*k)
{
if(i+k<=s.length())
{
reverse(c,i,i+k-1);
}
else
{
reverse(c,i,len-1);
}
}
return new String(c);
}
public void reverse(char[] c,int i,int j)
{
for(;i<j;i++,j--)
{
char temp=c[i];
c[i]=c[j];
c[j]=temp;
}
}
}
卡码网:54.替换数字
使用额外的空间
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String result="";
Scanner scanner=new Scanner(System.in);
String s=scanner.next();
char[] ch=s.toCharArray();
for(int i=0;i<s.length();i++)
{
if(ch[i]>='a'&& ch[i]<='z')
{
result+=ch[i];
}
else
{
result+="number";
}
}
System.out.println(result);
}
}
不使用额外的数组空间
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.next();
char[] ch = s.toCharArray();
int count = 0;
int OldIndex = ch.length - 1;
// 统计数字字符的数量
for (int i = 0; i < ch.length; i++) {
if (ch[i] >= '0' && ch[i] <= '9') {
count++;
}
}
// 扩容
char[] newS = new char[s.length() + count * 5];
// 已扩容的下标
int NewIndex = newS.length - 1;
while (OldIndex >= 0) {
if (ch[OldIndex] >= '0' && ch[OldIndex] <= '9') {
newS[NewIndex--] = 'r';
newS[NewIndex--] = 'e';
newS[NewIndex--] = 'b';
newS[NewIndex--] = 'm';
newS[NewIndex--] = 'u';
newS[NewIndex--] = 'n';
} else {
newS[NewIndex--] = ch[OldIndex];
}
OldIndex--;
}
System.out.println(new String(newS));
}
}
标签:卡码,ch,String,int,反转,lens,字符串,public
From: https://www.cnblogs.com/FreeDrama/p/18403278