字符串翻转
假设给定一个由字母和小数点组成的字符串,把字符串按块翻转,其中连续的小数点为一块,连续的字母为一块。例如 'ab..bc...cd.' 翻转后为 '.cd...bc..ab'
类似还有 'I am a sudent.' 翻转后为 'student. a am I '
php:
function change ($str) {
$block = "";
$new = "";
$b = false;
for ($i = strlen($str) - 1; $i >= 0; $i--) {
if ($str[$i] == ".") {
if ($b) {
$new .= strrev($block);
$block = "";
$b = false;
}
$new .= ".";
} else {
$block .= $str[$i];
$b = true;
}
}
if (!empty($block)) {
$new .= strrev($block);
}
return $new;
}
go:
package main
import (
"fmt"
)
func main() {
str :="ab..bc...cd."
fmt.Println(change(str))
}
func change(strstring)string {
var newstring
var block []rune
var bbool
runes := []rune(str)
dianRune := []rune(".")
for i :=len(runes) -1; i >=0; i-- {
if runes[i] == dianRune[0] {
if b {
new +=strrev(block)
block = []rune{}
b =false
}
new +="."
} else {
block =append(block, runes[i])
b =true
}
}
if len(block) >0 {
new +=strrev(block)
}
return new
}
func strrev(runes []rune)string {
for from, to :=0, len(runes)-1; from < to; from, to = from+1, to-1 {
runes[from], runes[to] = runes[to], runes[from]
}
return string(runes)
}