字符串相关
344.反转字符串
参考文章 题目链接
个人题解
class Solution {
public void reverseString ( char [ ] s) {
int l = 0 ;
int r = s. length - 1 ;
while ( l < r) {
swap ( s, l, r) ;
l++ ;
r-- ;
}
}
private void swap ( char [ ] s, int l, int r) {
char temp = s[ l] ;
s[ l] = s[ r] ;
s[ r] = temp;
}
}
541. 反转字符串II
参考文章 题目链接
个人题解
class Solution {
public String reverseStr ( String s, int k) {
char [ ] ch = s. toCharArray ( ) ;
for ( int i = 0 ; i < ch. length; i += ( 2 * k) ) {
if ( i + k <= s. length ( ) ) {
reverse ( ch, i, i + k - 1 ) ;
} else {
reverse ( ch, i, s. length ( ) - 1 ) ;
}
}
return new String ( ch) ;
}
public void reverse ( char [ ] ch, int i, int j) {
for ( ; i < j; i++ , j-- ) {
char temp = ch[ i] ;
ch[ i] = ch[ j] ;
ch[ j] = temp;
}
}
}
剑指Offer 05.替换空格
参考文章 题目链接
个人题解
class Solution {
public String replaceSpace ( String s) {
int count = 0 ;
for ( char c : s. toCharArray ( ) ) {
if ( c == ' ' ) {
count++ ;
}
}
if ( count == 0 ) {
return s;
}
char [ ] newChars = new char [ s. length ( ) + ( count * 2 ) ] ;
char [ ] oldChars = s. toCharArray ( ) ;
int newIndex = newChars. length - 1 ;
int oldIndex = s. length ( ) - 1 ;
while ( oldIndex >= 0 ) {
if ( oldChars[ oldIndex] == ' ' ) {
newChars[ newIndex-- ] = '0' ;
newChars[ newIndex-- ] = '2' ;
newChars[ newIndex] = '%' ;
} else {
newChars[ newIndex] = oldChars[ oldIndex] ;
}
oldIndex-- ;
newIndex-- ;
}
return new String ( newChars) ;
}
}
151.翻转字符串里的单词
参考文章 题目链接
个人题解
class Solution {
public String reverseWords ( String s) {
StringBuilder sb = removeSpace ( s) ;
reverseString ( sb, 0 , sb. length ( ) - 1 ) ;
reverseEachWord ( sb) ;
return sb. toString ( ) ;
}
private void reverseEachWord ( StringBuilder sb) {
int start = 0 ;
for ( int i = 0 ; i < sb. length ( ) ; i++ ) {
if ( sb. charAt ( i) == ' ' ) {
reverseString ( sb, start, i - 1 ) ;
start = i + 1 ;
}
}
if ( start != sb. length ( ) - 1 ) {
reverseString ( sb, start, sb. length ( ) - 1 ) ;
}
}
private void reverseString ( StringBuilder sb, int start, int end) {
while ( start < end) {
char temp = sb. charAt ( start) ;
sb. setCharAt ( start, sb. charAt ( end) ) ;
sb. setCharAt ( end, temp) ;
start++ ;
end-- ;
}
}
private StringBuilder removeSpace ( String s) {
StringBuilder sb = new StringBuilder ( ) ;
s = s. trim ( ) ;
for ( char c : s. toCharArray ( ) ) {
if ( c != ' ' || sb. charAt ( sb. length ( ) - 1 ) != ' ' ) {
sb. append ( c) ;
}
}
return sb;
}
}