Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. Example 1:
1 2
Input: "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
classSolution { public: string reverseWords(string s){ for (int i = 0; i < s.length(); i++) { if (s[i] != ' ') { // when i is a non-space int j = i; for (; j < s.length() && s[j] != ' '; j++) { } // move j to the next space reverse(s.begin() + i, s.begin() + j); i = j - 1; } } return s; } };
defvote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
解释
pk=request.POST['choice']这个参数表示,从request.POST请求中获取被选择的choice. 如果不存在的话,就抛出一个Choice.DoesNotExistChoice不存在的异常,错误信息为You didn’t select a choice.. 如果存在的话,那么这个choice的votes属性增加1并且使用save()函数写入数据库中. 在完成数据库写入操作之后,向页面发送了一个HttpResponseRedirect,将网页重定向到polls的results上,并且带上了当前的question的id. 这个函数也等效为重定向到'polls/question.id/results'这个页面. 接着我们来完善一下results函数:
from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect from django.urls import reverse from django.views import generic from .models import Choice, Question
classIndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' defget_queryset(self): """Return the last five published questions.""" return Question.objects.order_by('-pub_date')[:5]
classDetailView(generic.DetailView): model = Question template_name = 'polls/detail.html'
classResultsView(generic.DetailView): model = Question template_name = 'polls/results.html'
defvote(request, question_id): ... # same as above, no changes needed.