不用申請內(nèi)存空間铁坎,把一個(gè)字符串做反正操作蜂奸。
比如說:
str=”abcdefg”
res=”gfedcba”
這個(gè)比較簡單,只要做前后字符交換就可以了
func?reverse(str []byte){
????i := 0
????j := len(str) - 1
????for?i < j {
????????str[i], str[j] = str[j], str[i]
????????i ++
????????j --
????}
}
第二階段
不用申請內(nèi)存硬萍,如何把每個(gè)單詞做反轉(zhuǎn),假設(shè)單詞中間只有一個(gè)空格
比如說:
str = “php is the best programing language in the world”
res = “php si eht tseb gnimargorp egaugnal ni eht dlrow”
func reverse(str string) {
????i := 0
????k := 0
????reverse1 = func(str []byte, begin?int, end?int){
????????for?begin?< end?{
????????????str[begin], str[end] = str[end], str[begin]
????????????begin?++
????????????end?--
????????}
????}
????for?i = 0; i < len(str); i ++ {
????????if?str[i] == ' ' {
????????????reverse1(str, k, i - 1)
????????????k = i + 1
????????}
????}
}
第三階段
不用申請內(nèi)存扩所,如何把一組單詞做反轉(zhuǎn)。
比如說:
str = “php is the best programing language in the world”
res = “world the in language programing best the is php”
這個(gè)略有難度朴乖,但是只需要在第二階段的接觸上加一行代碼就可以做到了祖屏。
func?reverse(str string) {
????i := 0
????k := 0
????reverse1 = func(str []byte, begin int, end int){
????????for?begin < end {
????????????str[begin], str[end] = str[end], str[begin]
????????????begin ++
????????????end --
????????}
????}
????reverse1 (str, 0, len(str) - 1)
????for?i = 0; i < len(str); i ++ {
????????if?str[i] == ' '?{
????????????reverse1(str, k, i - 1)
????????????k = i + 1
????????}
????}
}